django admin相关字段无效查找:icontains

时间:2017-10-23 07:45:41

标签: django django-models django-admin

我有这些模特:

@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, )

我有这些管理对象:

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)

list_display工作正常,但搜索总是会出错:

Related Field got invalid lookup: icontains

我不知道自己做错了什么,我对SKU product_image_gallery__sku使用双下划线,但它仍然出错,我试过product_image_gallery这也是一个错误。

我的追踪:

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

2 个答案:

答案 0 :(得分:1)

原因是错误是因为

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

“the_image”是一个FilerImageField对象,它会导致错误。

当我把它变成:

时它会起作用
 search_fields       = ['id', 'title', 'product_image_gallery__sku']

答案 1 :(得分:1)

只是想澄清为什么会出现此错误。您正在尝试def create @course = current_user.courses.build(course_params) # You need to set @course.listing_id to an existing Listing # You need to find that listing and save it in a variable. # I am not getting into your logic, because your code is confused and need many adjustments listing = Listing.find() # include hear your logic to find an existing listing from the db @course.listing_id = listing.id if @course.save! redirect_to course_listing_path(@course), notice: "Saved..." else render :new, notice: "Something went wrong..." end end 上的允许搜索。但由于此字段的类型为the_image,因此Django无法为此类搜索提供可接受的查询。

幕后

这是来自Django文档:

  

当有人在管理搜索框中搜索时,Django会分割   将查询搜索到单词并返回包含每个对象的所有对象   单词不区分大小写,每个单词必须至少有一个   search_fields。

因此,如果您想允许搜索,您可能希望添加字段FilerImageField,我假设它是图像的名称。这样,人们就可以按名字搜索图像。

希望它有所帮助!