【发布时间】:2020-09-08 08:28:31
【问题描述】:
我有一个模型,其中字段 datetime 作为参考日期,字段整数包含从参考日期开始计算的天数,我需要过滤掉 reference_date + days 小于 django orm 中当前日期的行。我曾尝试使用 RawSQL,将过滤器委托给 mysql,但我需要访问行的一列,而且我不知道如何在 RawSql 表达式中包含 F 表达式,我尝试加入字符串但它不起作用.包括我的模型描述。
class ActionData(models.Model):
properties = models.ManyToManyField(Property, through='ActionProperties')
action = models.ForeignKey(Action, on_delete=models.CASCADE)
description = models.TextField(null=True)
days = models.IntegerField(default=0)
promocioned = models.BooleanField(default=False)
reference_date = models.DateTimeField(null=True)
modified_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
def __str__(self):
return str(self.pk) + self.action.name
【问题讨论】:
-
什么是
number_days和current_date?是这个模型(可能是几天)或相关模型上的那些奇异值或字段吗?如果它们在相关模型上,请同时包含它们。 -
对不起,current_date 是系统提供的实际日期,模型中的 number_days 是天数字段,我会编辑问题。另外我认为我解决了这样构建查询集的问题:
qset = ActionData.objects.filter(reference_date__lt = RawSQL('DATE_SUB(CURDATE(), INTERVAL %s DAY)', [F('days')]))但我还不确定。谢谢
标签: python django django-queryset rawsql