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

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

django - Search by foreign key in admin

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...