nilved
nilved

Reputation: 63

Django search_fields & Many-To-One Relations

As an example, I have two models: Household and Person:

from django.db import models
class Household(models.Model):
    address = # ...
class Person(models.Model):
    household = models.ForeignKey(Household)
    name = # ...

How can I search for Households by names of Persons inside the Django admin?

Upvotes: 0

Views: 1570

Answers (1)

eternicode
eternicode

Reputation: 6935

As mentioned in the docs for search_fields:

You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API "follow" notation:

search_fields = ['foreign_key__related_fieldname']

For example, if you have a blog entry with an author, the following definition would enable search blog entries by the email address of the author:

search_fields = ['user__email']

This should also work "backwards", as in your example.

search_fields = ['person__name']

Upvotes: 7

Related Questions