Django按日期筛选datetime字段时出错:不允许在字段X上加入



我看到另一篇文章建议可以使用__date按时间过滤日期时间字段。然而,当我试用我的机器时,它一直不起作用。

这是我的models.py

class Record (models.Model):
    time = models.DateTimeField(null=True,blank=True)
    user = ForeignKey to the user table
    content = models.CharField(max_length=36,null=True,blank=True,unique=True)

python manage.py.runserver

>>> from datetime import datetime
>>> from appname.models import Record
>>> u = User.objects.filter(username = 'user')
>>> r = Record.objects.filter(time__date = datetime.today().date())
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:Python27libsite-packagesdjangodbmodelsmanager.py", line 163, in filter
    return self.get_queryset().filter(*args, **kwargs)
  File "C:Python27libsite-packagesdjangodbmodelsquery.py", line 590, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "C:Python27libsite-packagesdjangodbmodelsquery.py", line 608, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "C:Python27libsite-packagesdjangodbmodelssqlquery.py", line 1198, in add_q
    clause = self._add_q(where_part, used_aliases)
  File "C:Python27libsite-packagesdjangodbmodelssqlquery.py", line 1234, in _add_q
    current_negated=current_negated)
  File "C:Python27libsite-packagesdjangodbmodelssqlquery.py", line 1100, in build_filter
    allow_explicit_fk=True)
  File "C:Python27libsite-packagesdjangodbmodelssqlquery.py", line 1357, in setup_joins
    names, opts, allow_many, allow_explicit_fk)
  File "C:Python27libsite-packagesdjangodbmodelssqlquery.py", line 1320, in names_to_path
    "the lookup type?" % (name, names[pos + 1]))
FieldError: Join on field 'timeIn' not permitted. Did you misspell 'date' for the lookup type?

我在windows 7上运行python 2.7,django 1.6

非常感谢您的帮助!

请注意,这应该从Django 1.9开始工作。

Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))

使用__contains而不是__date:

r = Record.objects.filter(time__contains = datetime.today().date())

更新

由于__startswith(LIKE'value%')比__contains(LIKE'%value%')更快,因此最好的选择是:

r = Record.objects.filter(time__startswith = datetime.today().date())

相关内容

  • 没有找到相关文章

最新更新