Search code examples
djangodjango-modelsforeign-keysdjango-admin

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


Solution

  • 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