Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Search related fields

My models:

class Contact(models.Model):
    first_name = models.CharField(_("First name"), max_length=30, )
    last_name = models.CharField(_("Last name"), max_length=30, )
    email = models.EmailField(_("Email"), blank=True, max_length=75)

class PhoneNumber(models.Model):
    contact = models.ForeignKey(Contact)
    phone = models.CharField(_("Phone Number"), blank=True, max_length=30, )
    primary = models.BooleanField(_("Primary"), default=False)

My admin.py:

class ContactOptions(AutocompleteAdmin):
    list_display = ('last_name', 'first_name')
    ordering = ['last_name']
    search_fields = ('first_name', 'last_name', 'email')
    related_search_fields = { """??? I want to search the Phone Numbers ???""" }

How to search the Phone Numbers in Django admin? Please give some code. Thank you very much!

like image 534
anhtran Avatar asked Aug 26 '10 08:08

anhtran


2 Answers

Just in case someone comes over this question, in Django 1.6, search in reverse relation is indeed possible.

In your phone model add related_name="phonesList" to contact field

contact = models.ForeignKey(Contact, related_name="phonesList")

Now in search_field you can use the double undescore to go from conatct to phones like this: phonesList__phone

search_fields = ('first_name', 'last_name', 'email','phonesList__phone')
like image 145
elsadek Avatar answered Oct 10 '22 00:10

elsadek


UPDATE: this answer is outmoded, see the answer from elsadek instead


You're asking to be able to follow a reverse relation (ie, from PhoneNumber back to Contact) but I don't believe the double-underscore __ trick for spanning tables will work here.

If your Contact had the key to the PhoneNumber model instead of the current set-up:

class Contact(models.Model):
    ...
    phone = models.ForeignKey(PhoneNumber)

then in the admin config you could do:

search_fields = ('first_name', 'last_name', 'email', 'phone__phone')
like image 43
Steve Jalim Avatar answered Oct 09 '22 23:10

Steve Jalim