Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django Admin Search field reverse lookup

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

@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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading