175

I have the following models in models.py:

class ListinoTraduttore(models.Model):
        traduttore = models.ForeignKey('Traduttore', related_name='Traduttore')
        linguaDa = models.ForeignKey(Lingua, related_name = "linguaDa")
        linguaA = models.ForeignKey(Lingua, related_name = "linguaA")
        prezzoParola = models.CharField(max_length=50, blank=True)
        prezzoRiga = models.CharField(max_length=50, blank=True)
        scontoCat = models.CharField(max_length=50, blank=True)
        scontoFuzzy = models.CharField(max_length=50, blank=True)
        scontoRipetizioni = models.CharField(max_length=50, blank=True)
        class Meta:
                verbose_name_plural = "Listini Traduttori"
        def __unicode__(self):
                return u"%s Da %s A %s Parola=%s Riga=%s ScontoCAT=%s ScontoFuzzy=%s ScontoRipetizioni=%s" % (self.traduttore, self.linguaDa, self.linguaA, self.prezzoParola, self.prezzoRiga, self.scontoCat, self.scontoFuzzy, self.scontoRipetizioni)


class Traduttore(models.Model):
        nome = models.CharField(nomeString, max_length=50)
        cognome = models.CharField(cognomeString, max_length=50)
        nomeAzienda = models.CharField(nomeAziendaString, max_length=50, blank=True)
        codiceFiscale = models.CharField(codiceFiscaleString, max_length=50, blank=True)
        partitaIva = models.CharField(partitaIvaString, max_length=50, blank=True)
        indirizzo = models.CharField(indirizzoString, max_length=50, blank=True)
        telefono = models.CharField(telefonoString, max_length=50, blank=True)
        fax = models.CharField(faxString, max_length=50, blank=True)
        email = models.EmailField(max_length=50, blank=True)
        referente = models.CharField(referenteString, max_length=50, blank=True)
        valuta = models.ForeignKey(Valuta)
        metodoPagamento = models.ForeignKey(MetodoPagamento)
        datiBancari = models.CharField(datiBancariString, max_length=50, blank=True)
        programmiUtilizzati = models.ManyToManyField(Programma, blank=True)
        note = models.CharField(max_length=200, blank=True)
        listino = models.ManyToManyField(ListinoTraduttore, related_name='listino', blank=True)
        def __unicode__(self):
                return u"%s %s %s" % (self.nome, self.cognome, self.nomeAzienda)
        class Meta:
                verbose_name_plural = "Traduttori"

While in the admin.py I have the following:

class TraduttoreAdmin(admin.ModelAdmin):
        list_display = ("nome", "cognome", "nomeAzienda")
        search_fields = ["nome", "cognome", "nomeAzienda"]

class ListinoTraduttoreAdmin(admin.ModelAdmin):
        list_display = ("traduttore", "linguaDa", "linguaA", "prezzoParola", "prezzoRiga", "scontoCat", "scontoFuzzy", "scontoRipetizioni")
        search_fields = ['traduttore__nome", "linguaDa", "linguaA"]

But when I try to make a search in the admin page in the ListinoTraduttore table I have the following error:

TypeError at /admin/itrad/listinotraduttore/
Related Field has invalid lookup: icontains
Request Method: GET
Request URL:    http://127.0.0.1:8000/admin/itrad/listinotraduttore/?q=Fenicio
Django Version: 1.4.1
Exception Type: TypeError
Exception Value:    
Related Field has invalid lookup: icontains
Exception Location: /Library/Python/2.7/site-packages/django/db/models/fields/related.py in get_prep_lookup, line 142
Python Executable:  /usr/bin/python
Python Version: 2.7.2
Python Path:    
['/Users/nicolac/Documents/DjangoProjects/mysite',
 '/Library/Python/2.7/site-packages/pip-1.1-py2.7.egg',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC',
 '/Library/Python/2.7/site-packages']
djvg
  • 11,722
  • 5
  • 72
  • 103
user1545895
  • 1,761
  • 2
  • 11
  • 5

11 Answers11

225

This is to (hopefully) simplify the answer.

Don't filter on a ForeignKey field itself!


Change this

search_fields = ['foreignkeyfield']

to this (notice TWO underscores)

search_fields = ['foreignkeyfield__name']

name represents the field-name from the table that we have a ForeignKey relationship with.

starball
  • 20,030
  • 7
  • 43
  • 238
Dror
  • 5,107
  • 3
  • 27
  • 45
  • 3
    It is the answer I want, BTW, I tried: `search_fields = ['foreinkeyfield__foreinkeyfield__name']`, it works too. thanks – C.K. Mar 30 '19 at 18:28
202

Have you tried adding the __fieldname on those Lingua references in the ListinoTraduttoreAdmin search_fields, like:

class ListinoTraduttoreAdmin(admin.ModelAdmin):        
    list_display = ("traduttore", "linguaDa", "linguaA", "prezzoParola", "prezzoRiga", "scontoCat", "scontoFuzzy", "scontoRipetizioni")
    search_fields = ['traduttore__nome", "linguaDa__field1", "linguaA_field2"]
furins
  • 4,979
  • 1
  • 39
  • 57
bskinnersf
  • 3,090
  • 1
  • 20
  • 10
  • 7
    it's just a really unhelpful error message. This was basically the solution in my case. for reference https://code.djangoproject.com/ticket/2331 – seans Jan 18 '13 at 20:05
  • 7
    This was the correct answer for me. Fixed this issue when I did a search on any FOREIGN KEY. Thanks – cnobile Dec 19 '13 at 14:29
  • 1
    This should be the accepted answer, as @seans mentioned, this error occurs every time there is a foreign key on the search_fields (django 1.11). – Cyrlop Mar 12 '18 at 17:52
  • 3
    6 years later that crappy error message is still there! – rbennell Sep 28 '18 at 10:48
  • 2
    8 years later, that message still kills us – Hritik Aug 12 '21 at 23:56
83

Use Django's double underscore convention instead. docs foreignkeyfield__name

Make sure you are not adding any Foreignkey or ManyToManyField to your search_field directly.

class ListinoTraduttoreAdmin(admin.ModelAdmin):
    list_display = ("traduttore", "linguaDa", "linguaA", "prezzoParola", "prezzoRiga", "scontoCat", "scontoFuzzy", "scontoRipetizioni")
    search_fields = ['traduttore__nome", "linguaDa__field1", "linguaA__field2"]
Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Kwaw Annor
  • 1,448
  • 13
  • 13
  • 16
    This was an important note! So if you want to search a ForeignKey, you should explicitely serch for the attributes there (e.g. my_related_object__first_attribute). – OBu Oct 03 '13 at 06:07
12

Double underscore needed

class exampleAdmin(admin.ModelAdmin):
 search_field = ('yourforeignkeyname__choosefieldnameinyourforeignkey')
mechnicov
  • 12,025
  • 4
  • 33
  • 56
Azmol
  • 399
  • 4
  • 6
3

This worked for me.

Search the field of the foreign key using my_related_object__first_attribute:

search_fields = ('author__username', 'title')
from models
author = models.ForeignKey(User, on_delete=models.CASCADE,   related_name='blog_posts2')
Taazar
  • 1,545
  • 18
  • 27
Ibby
  • 69
  • 4
1

This error, mostly occurs when you try to filter using a ForeignKey. I think the error is in the search_filelds. Check it. search_fields = ['traduttore__nome", "linguaDa", "linguaA"]. This two ForeignKey ("linguaDa", "linguaA") are the problem. Remove them. I think this helps.

Edem Robin
  • 43
  • 5
1

This may not answer the original question, but, every so often I run into a similar invalid lookup error because I accidentally used _set in a lookup, e.g. <model_name>_set instead of just <model_name>.

Basically, I tend to confuse the related_query_name with the default_related_name , which does include _set (also see queries docs and related manager docs).

From the lookups documentation:

It works backwards, too. Whilst it can be customized, by default you refer to a “reverse” relationship in a lookup using the lowercase name of the model.

(my emphasis)

Confusing thing is that the default related_name (i.e. <model_name>_set) is not the same as the default related_query_name (i.e. <model_name>), but if you set a custom related_name (or default_related_name, via model Meta options), that will also be used as the default related_query_name (as mentioned in the docs).

djvg
  • 11,722
  • 5
  • 72
  • 103
1

I stayed up all night looking for the solution and I found it at last.

This error occurs when you want to search a onetoonefield, foreignkey, or manytomanyfield.

The solution is:

search_feild = [<foreignkeyfeild>__<foreignkey name as it is in the main model>]

for example:

class FranchiseManager(AbstractBaseUser):

    BRANCH_MANAGER = "BR"
    EMPLOYEE = "EMP"

    DESIGNATION = [
        (BRANCH_MANAGER, "Branch manager"),
        (EMPLOYEE, "Employee")
    ]

    company = models.ForeignKey(MainManager, 
              on_delete=models.CASCADE, primary_key=True)
              first_name = models.CharField(max_length=128, 
                          blank=True)
    last_name = models.CharField(max_length=128, blank=True)
    designation = models.CharField(max_length=20, 
    choices=DESIGNATION)
    branch = models.CharField(max_length=200, blank=True)
    date = models.DateTimeField(default=timezone.now)
    is_admin = models.BooleanField(default=False)

    USERNAME_FIELD = "first_name"

    def __str__(self):
        return self.first_name


class ProductCategories(models.Model):
     manager = models.ForeignKey(FranchiseManager, 
               on_delete=models.CASCADE)
     name = models.CharField(max_length=200)

     def __str__(self):
        return f" {self.name} :-: {self.manager}"

Then search search will be as follows:

search_fields = ["manager__first_name"]
Chiemerie
  • 11
  • 3
  • I found a mistake in your code. You have single quote at the beginning of and double at the end of the string 'traduttore__nome" – Chiemerie Mar 13 '23 at 08:56
0

it may be weird

search_fields = ['traduttore__nome']

giving like this , with single quotes will create error.

search_fields = ["traduttore__nome"]

giving with double quotes will fix the issue

foreignkeyfield__lookupfield  - this is the format
0

Please check if the field either exists in the model or not, if not, then remove the search field from the search list. Then, check if the search field value is either a foreign key or not, if any field is a foreign key, then please add the foreign key's field name like ForeignKey__FieldName (FieldName is the very field you wanna search).

-3

add in admin.py

admin.site.register(Traduttore, TraduttoreAdmin)
admin.site.register(ListinoTraduttore, ListinoTraduttoreAdmin)

see the link https://docs.djangoproject.com/en/dev/intro/tutorial02/

  • Hi, I did it but nothing change. I have the same error. Do you have any other suggestions? – user1545895 Aug 01 '12 at 12:03
  • 2
    This does not work. What we need to access is the foreign key field. which can be looked up as follows. ` [foreignfield__name]` – Laban Feb 07 '20 at 06:51