Home > database >  Django Admin Search field reverse lookup
Django Admin Search field reverse lookup

Time:02-18

I have following models:

class Policy(models.Model):
    name = models.CharField(max_length=40)

    def __str__(self) -> str:
        return self.name

    class Meta:
        verbose_name_plural = 'Policies'

class Statement(models.Model):
    name = models.CharField(max_length=40)
    policy = models.ForeignKey(
        to=Policy,
        on_delete=models.CASCADE,
        related_name='statements'
    )
    action = models.CharField(max_length=64)
    resource = models.CharField(max_length=128)

and following simple model admin:

class PolicyAdmin(admin.ModelAdmin):
    inlines = [StatementInline]
    search_fields = [name,]
    class Meta:
        model = Policy

What I want to achieve is to enable search functionality on Policy change list, through which I can search Policy with the name field of Statement model in addition to policy name.

CodePudding user response:

@admin.register(Policy)
class ExapmleAdmin(admin.ModelAdmin):
    search_fields = ("statements__name",)
    class Meta:
        model = Policy

admin.site.register(Statement)

On your admin.py file. You can search Policy with the name field of Statement model like this.

  • Related