首页 > 解决方案 > Django:如何解决“关键字不能是表达式”错误

问题描述

在下面的代码中,capitals_listings_from_latest_Celery_scrape是一个Listing模型对象的 QuerySet:

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

但是,我目前得到

“关键字不能是表达式”

由于date_added.date()部分原因,此行有错误。

我使用的原因.date()是为了正确评估我需要从时间数据中剥离date_added并只留下年、月和日。latest_Celery_scrape_datedate_added

如何修复错误?

标签: pythondjangopython-datetime

解决方案


问题是您将调用作为关键字(参数名称),而参数名称应该是标识符:

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

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

>>> id(id()=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__date=latest_Celery_scrape_date
)

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

__date如查找文档中所述:

When USE_TZis True,字段在过滤前转换为当前时区。


推荐阅读