Django按日期过滤日期时间字段时出错:不允许在字段X上进行连接

0 投票
2 回答
3907 浏览
提问于 2025-04-18 04:41

我看到另一个帖子提到,可以通过使用 __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

用 __contains 替代 __date:

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

更新

因为 __startswith (像 'value%') 比 __contains (像 '%value%') 更快,所以最好的选择是:

r = Record.objects.filter(time__startswith = datetime.today().date())
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))

撰写回答