Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django admin related Field got invalid lookup: icontains

I got these Models:

@python_2_unicode_compatible
class Media(models.Model):
  the_image   = FilerImageField(null=True)
  title       = models.CharField(verbose_name="Title", max_length=255, null=True, blank=True)
  alt_text    = models.CharField(verbose_name="Alt Text", max_length=255, null=True, blank=True)

  created     = models.DateTimeField(default=now)
  modified    = models.DateTimeField(editable=True, auto_now=True)

  product_image_gallery   = models.ForeignKey('Product', related_name="product_image_gallery", null=True, blank=True, verbose_name="Product's Image Gallery")

  def __str__(self):
     return self.the_image.__str__()

@python_2_unicode_compatible
class Product( models.Model ):
  name    = models.CharField(verbose_name="Name", max_length=255)
  slug    = models.SlugField(verbose_name="Slug", max_length=255, unique=True)
  price       = models.PositiveIntegerField(verbose_name='Price', null=True, blank=True)
  sale_price  = models.PositiveIntegerField(verbose_name="Sale Price", null=True, blank=True)
  sku = models.CharField(verbose_name="SKU", max_length=255)

  def __str__(self):
    return "%s" % (self.sku, )

I have these Admin Objects:

class Media_Admin(admin.ModelAdmin):
  search_fields       = ['id', 'the_image', 'title', 'product_image_gallery__sku']
  list_display        = ['the_image', 'image_tag', 'title', 'product_image_gallery', 'created']
  readonly_fields     = ('image_tag',)
  fieldsets = [
    ( "Data", {
        'classes': ('grp-collapse grp-open',),
        'fields': ['the_image', 'title', 'alt_text']}),
  ]
admin.site.register(Media, Media_Admin)

The list_display works fine but the search always gives an error saying:

Related Field got invalid lookup: icontains

I don't know what I did wrong, I use double underscore for the SKU product_image_gallery__sku, but it still gives an error, I tried product_image_gallery it is also an error.

My Trace:

Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/mooimom_id/media/?q=A7005

Django Version: 1.10.7
Python Version: 2.7.13
Installed Applications:
['corsheaders',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.humanize',
 'tinymce',
 'easy_thumbnails',
 'filer',
 'mptt',
 'storages',
 'django_extensions']
    Installed Middleware:
    ['corsheaders.middleware.CorsMiddleware',
 'htmlmin.middleware.HtmlMinifyMiddleware',
 'htmlmin.middleware.MarkRequestMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'mooimom_django.mooimom_middleware.SimpleMiddleware',
 'ratelimitbackend.middleware.RateLimitMiddleware']



Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
 42.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
 185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in wrapper
 544.                 return self.admin_site.admin_view(view)(*args, **kwargs)

File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

 File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)

File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in inner
  211.             return view(request, *args, **kwargs)

File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapper
  67.             return bound_func(*args, **kwargs)

File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

File "C:\Python27\lib\site-packages\django\utils\decorators.py" in bound_func
  63.                 return func.__get__(self, type(self))(*args2, **kwargs2)

 File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in changelist_view
  1543.                 self.list_max_show_all, self.list_editable, self,

File "C:\Python27\lib\site-packages\django\contrib\admin\views\main.py" in __init__
78.         self.queryset = self.get_queryset(request)

File "C:\Python27\lib\site-packages\django\contrib\admin\views\main.py" in get_queryset
  346.         qs, search_use_distinct = self.model_admin.get_search_results(request, qs, self.query)

File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in get_search_results
  905.                 queryset = queryset.filter(reduce(operator.or_, or_queries))

File "C:\Python27\lib\site-packages\django\db\models\query.py" in filter
  796.         return self._filter_or_exclude(False, *args, **kwargs)

 File "C:\Python27\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
  814.             clone.query.add_q(Q(*args, **kwargs))

 File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_q
   1227.         clause, _ = self._add_q(q_object, self.used_aliases)

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in _add_q
   1247.                     current_negated, allow_joins, split_subq)

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in _add_q
  1253.                     allow_joins=allow_joins, split_subq=split_subq,

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_filter
   1178.             lookup_class = field.get_lookup(lookups[0])

File "C:\Python27\lib\site-packages\django\db\models\fields\related.py" in get_lookup
   694.             raise TypeError('Related Field got invalid lookup: %s' % lookup_name)

Exception Type: TypeError at /admin/mooimom_id/media/
Exception Value: Related Field got invalid lookup: icontains
like image 992
Raymond Seger Avatar asked Oct 23 '17 07:10

Raymond Seger


Video Answer


2 Answers

Turns out the error is because of

search_fields       = ['id', 'the_image', 'title', 'product_image_gallery__sku']

"the_image" is a FilerImageField object, it causes the error.

It works when i turned it into:

 search_fields       = ['id', 'title', 'product_image_gallery__sku']
like image 63
Raymond Seger Avatar answered Oct 22 '22 16:10

Raymond Seger


Just wanted to clarify on why this error occured. You were trying the allow searching on the_image. But since this field is of type FilerImageField Django cannot provide an acceptable query for this kind of search.

Behind the scene

This is from Django documentation:

When somebody does a search in the admin search box, Django splits the search query into words and returns all objects that contain each of the words, case insensitive, where each word must be in at least one of search_fields.

Therefore, if you want to allow search, you probably want to add the field title instead, which I assumed is the name of the image. This way, people will be able to search image by their name.

Hope it helps !

like image 22
scharette Avatar answered Oct 22 '22 18:10

scharette