【发布时间】:2017-06-14 19:53:09
【问题描述】:
我想在 DjangoORM 中使用注释创建一个名为 notification_date 的新字段。
这是我的模型:
SpeciesType(models.Model):
# ... some species type setting fields.
heat_lapse = IntegerField()
estrous = IntegerField()
Breeding(models.Model):
# .. some breeding fields
species_type = ForeignKey(SpeciesType, related_name="breedings", on_delete=CASCADE)
created_at = DateTimeField(auto_add_now=True)
现在育种日期通知的公式是
Breeding.created_at + (SpeciesType.heat_lapse * SpeciesType.estrous) in days
e.g. 1/29/2017 11:21PM + (3 * 21) in days = 4/2/2017 as notification date
所以为了实现这一点,我使用 timedelta、F() 对象和 ExpressionWrapper 创建了这个查询过滤器:
from django.db.models import F, ExpressionWrapper, DateField
from datetime import date, timedelta
Breeding.objects.annotate(
notification_date = ExpressionWrapper(
F('created_at') +
timedelta(days=(
F('species_type__heat_lapse') * F('species_type__estrous')
))
, output_field=DateField())
).filter(
notification_date__lte == date.today()
)
但这不起作用,因为您不能在 timedelta 内执行 F()。任何人都知道如何制定这个所需的查询?这对我有很大的帮助。
【问题讨论】:
标签: django python-2.7 django-queryset django-orm django-filter