jac300
jac300

Reputation: 5222

Reverse Relation Search Django Admin Interface

Is it possible to do a reverse relation search on the Django Admin interface?

My Django app database schema consists of the following models:

class Tag(models.Model):
    title = models.CharField(max_length=50)

class Publication(models.Model):
    title = models.CharField(max_length=200)
    tags = models.ManyToManyField(Tag, blank=True, related_name="publications")

I have added a search field for looking up tags by title in my admin.py file by doing:

class TagAdmin(admin.ModelAdmin):
    list_display = ('title',)
    search_fields = ('title',)

Thus, when I type a tag title into the search field on the django admin interface, a list of matching tag titles comes up. Now I'd like to make it so that if I type a tag title into the search field, matching publications come up.

In other words, I'm imagining something like:

 class TagAdmin(admin.ModelAdmin):
    list_display = ('title',)
    search_fields = ('publications',)

Which of course doesn't work... but that's the idea...

Is this even possible? And/or am I even going about this the right way? If so, could someone suggest a way to do this or a resource? If you are kind enough to do so, please keep in mind that I am very much a beginner. Thanks.

Upvotes: 3

Views: 1420

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37354

You shouldn't try to do this using an admin class registered to your Tag model. Instead, set up an admin class for Publication and set its search_fields:

class PublicationAdmin(admin.ModelAdmin):
    list_display = ('title',)
    search_fields = ('tags__title',)

Upvotes: 3

Related Questions