按日期过滤日期时间字段时出现Django错误:不允许在字段X上加入

时间:2014-04-29 04:11:15

标签: python sql django datetime

我看到另一篇帖子建议可以使用__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:\Python27\lib\site-packages\django\db\models\manager.py", line 163, in filter
    return self.get_queryset().filter(*args, **kwargs)
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 590, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 608, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 1198, in add_q
    clause = self._add_q(where_part, used_aliases)
  File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 1234, in _add_q
    current_negated=current_negated)
  File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 1100, in build_filter
    allow_explicit_fk=True)
  File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 1357, in setup_joins
    names, opts, allow_many, allow_explicit_fk)
  File "C:\Python27\lib\site-packages\django\db\models\sql\query.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

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

抬头,这应该从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))

答案 1 :(得分:0)

使用__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())