Django:如何解决 "Keyword can't be an expression" 错误

Django: how to work around "Keyword can't be an expression" error

在下面的代码中,capitals_listings_from_latest_Celery_scrapeListing 个模型对象的查询集:

capitals_listings_from_latest_Celery_scrape = capitals_listings_all.filter(date_added.date()=latest_Celery_scrape_date)

但是,我目前得到

"Keyword can't be an expression"

这一行的错误,因为 date_added.date() 部分。

我使用 .date() 的原因是为了根据 latest_Celery_scrape_date 正确评估 date_added 我需要从时间数据中删除 date_added 并只留下年份, 月和日。

如何修复错误?

问题是你调用关键字(参数名),而参数名应该是一个标识符:

capitals_listings_from_latest_Celery_scrape = capitals_listings_all.filter(
    <s><b>date_added.date()</b></s>=latest_Celery_scrape_date
)

如果你使用这样的语法,你确实会得到这个错误,例如:

>>> id(<b><s>id()</s></b>=3)
  File "", line 1
SyntaxError: keyword can't be an expression

Django 对此有一个查找:__date [Django-doc] 查找。所以你可以这样查询:

capitals_listings_from_latest_Celery_scrape = capitals_listings_all.filter(
    date_added<b>__date</b>=latest_Celery_scrape_date
)

但是请注意,时间戳的 date 本身就是一个复杂的问题,因为人们可以旨在找到特定时区内的日期,或者 [=30= 中的该时间戳的数据]当前时区。

__date 查找文档中所指定:

When USE_TZ is True, fields are converted to the current time zone before filtering.