Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

models.py

class Supplier(models.Model):
   name = models.CharField(blank=True, max_length=50,)
   city = models.CharField(blank=True, max_length=50)
   email = models.CharField(blank=True, max_length=50)

class Product(models.Model):
   supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
   description = models.CharField(blank=True, max_length=100)
   DDT = models.FileField(upload_to="DDT/%Y/%m/%d")
   fattura = models.FileField(upload_to="DDT/%Y/%m/%d")

admin.py
     
@admin.register(Supplier)
    class SupplierModelAdmin(admin.ModelAdmin):
    model = Supplier
  
@admin.register(Product)
    class ProductModelAdmin(admin.ModelAdmin):
    model = Product
    list_display = ['supplier']
    search_fields = [ 'supplier']

when i search for a supplier , django return an error :

Related Field got invalid lookup: icontains


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.8k views
Welcome To Ask or Share your Answers For Others

1 Answer

You can do this using the __ notation.

So you'd do;

@admin.register(Product)
    class ProductModelAdmin(admin.ModelAdmin):
    model = Product
    list_display = ['supplier']
    search_fields = [
        'description',
        'supplier__name',
        'supplier__city',
        'supplier__email'
    ]

Docs for search are here; https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...