如何将datetimefield添加到admin changelist的search_fields

时间:2011-08-12 09:40:27

标签: django datetime django-admin

在管理员的模型更改列表页面中,我向search_fields添加了DateTimeField“birth”。

class DataLog(models.Model):
    id = models.AutoField(primary_key=True, verbose_name="idd")
    birth = models.DateTimeField(auto_now_add=True, verbose_name="create_time") 

class DataLogAdmin(admin.ModelAdmin):
    search_fields = ['id', 'birth', ]

添加时效果很好。但今天出现了一个错误:

Warning at /admin/data/log/
    Incorrect datetime value: '%2011-07-12%' for column 'birth' at row 1
    Django Version:     1.2.3
    Exception Location: /usr/lib/python2.5/warnings.py in warn_explicit, line 102

这是db sql:

u'SELECT COUNT(*) FROM `data_log` WHERE (`data_log`.`id` LIKE %2011-07-12% OR `data_log`.`birth` LIKE %2011-07-12% )'

我从那以后编辑了我的django的项目。

所以我不知道是什么原因引起的。

这是我的问题:

  • 将datetimeField插入django支持的search_fields?
  • 这样做的正确方法是什么?
  • 关于我的错误的任何想法?

新进展:

我测试了那个sql。

在Mysql中,它运行良好。 (mysql的命令行和Django的dbshel​​l都是)

mysql> SELECT COUNT(*) FROM `data_log` WHERE (`data_log`.`id` LIKE '%07-19%' OR `data_log`.`birth` LIKE '%07-19%' );
+----------+
| COUNT(*) |
+----------+
|        3 | 
+----------+
1 row in set, 1 warning (0.00 sec)

但是在django shell中,同样的错误:

User.objects.raw("SELECT COUNT(*) FROM `data_log` WHERE (`data_log`.`id` LIKE '%%07-19%%' OR `data_log`.`birth` LIKE '%%07-19%%' )")[0]

Traceback (most recent call last):
 File "<console>", line 1, in <module>
 File "/usr/lib/python2.5/site-packages/django/db/models/query.py", line 1379, in __getitem__
   return list(self)[k]
 File "/usr/lib/python2.5/site-packages/django/db/models/query.py", line 1372, in __iter__
   for row in self.query:
 File "/usr/lib/python2.5/site-packages/django/db/models/sql/query.py", line 73, in __iter__
   self._execute_query()
 File "/usr/lib/python2.5/site-packages/django/db/models/sql/query.py", line 87, in _execute_query
   self.cursor.execute(self.sql, self.params)
 File "/usr/lib/python2.5/site-packages/django/db/backends/util.py", line 15, in execute
   return self.cursor.execute(sql, params)
 File "/usr/lib/python2.5/site-packages/django/db/backends/mysql/base.py", line 86, in execute
   return self.cursor.execute(query, args)
 File "/var/lib/python-support/python2.5/MySQLdb/cursors.py", line 168, in execute
   if not self._defer_warnings: self._warning_check()
 File "/var/lib/python-support/python2.5/MySQLdb/cursors.py", line 82, in _warning_check
   warn(w[-1], self.Warning, 3)
 File "/usr/lib/python2.5/warnings.py", line 62, in warn
   globals)
 File "/usr/lib/python2.5/warnings.py", line 102, in warn_explicit
   raise message
Warning: Incorrect datetime value: '%07-19%' for column 'birth' at row 1

3 个答案:

答案 0 :(得分:2)

好吧......我自己找到了答案。

    Warning: Incorrect datetime value: '%123%' for column 'birth' at row 1
  • 在mysql中,使用LIKE for datetime字段有效,但不是推荐。所以,上面总是有警告。 http://bugs.mysql.com/bug.php?id=38915

  • 在Django中,如果我们在 settings.py 中设置“ Debug = True ”,则django会将此警告视为错误。

因此,该模型的所有搜索都会失败。

我会将DateTimeField保留在search_fields中,但仅用于非调试服务器。


对于我在标题中的原始问题,答案是:

  • 只需将DateTimeField添加到search_fields,它适用于非调试服务器

答案 1 :(得分:1)

根据:

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields

搜索字段必须是某种文本字段,如CharField或TextField。您可以使用foreignkeys等进行相关查找,但不能与其他字段类型进行相关查找。

从Django 1.6开始,您可以自定义管理搜索的get_search_results()。因此,在定义我的管理类时,我从search_fields中取消了日期字段,而是包括:

def get_search_results(self, request, queryset, search_term):
    # Try to filter by year of purchase
    try:
        int_term = int(search_term)
        queryset |= self.model.objects.filter(birth__year=int_term)
    except:
        pass
    return queryset, use_distinct

当然,这只会按年份返回结果,但如果你愿意,你绝对可以获得幻想。实际上,这不是理想的解决方案,但是一旦你开始考虑它,按日期搜索是一个非常直观的过程。

答案 2 :(得分:0)

  
      
  1. 日期或日期时间字段不是字符串类型
  2.   
  3. admin.search_fields 仅支持字符串类型的字段或相关字段
  4.   
  5. 但是我们仍然可以通过覆盖get_search_results
  6. 来搜索日期   
  7. see django docs
  8.   
# app/admin.py

class MaterialAdmin(admin.ModelAdmin):
    ....
    # Don't need to enter 'date'
    search_fields = ('supplier__name', 'service_name')

    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super().get_search_results(request, queryset, search_term)
        try:
            import datetime as dt
            import pytz
            date_obj = dt.datetime.strptime(search_term, '%Y年%m月%d日').date()
            # date_obj = dt.datetime.strptime(search_term, '%Y-%m-%d').date() # choose your own date format
            # date_time_obj = dt.datetime.strptime(search_term,  '%Y-%m-%d %H:%M:%S') # if you want to search datetime field
        except ValueError:
            pass
        else:
            queryset |= self.model.objects.filter(date=date_obj)
            # queryset |= self.model.objects.filter(date=date_time_obj)     # if search datetime
        return queryset, use_distinct

在Django 2.1.7中测试