繁体   English   中英

在 django orm 查询中使用 model 方法

[英]using model method in the django orm query

我有一个 model,它有一个名为 cancelled_date 的 model 方法,它返回取消模型中的记录时的日期如何在我的查询集中访问此方法以获取特定数据。

class Record(models.Model):
    name = models.CharField(max_length=255)
    
    def cancellation_date(self):
        return cancelled_date

function 取消日期返回当天记录被取消的日期

我想从记录 model 中过滤取消日期并做一些事情

records = Record.objects.all()
for record in records:
    if record.cancellation_date() == timezone.now()

我可以像这样访问,但是有没有一种方法可以只过滤设置为今天日期的记录 cancel_date

您不能在.filter()中使用 Model class 中定义的方法。

您可以改用注释:

Record.objects.annotate(
    annotated_cancellation_date=datetime.today() #assign the desired value using orm funcions
).filter(
    annotated_cancellation_date=datetime.today()
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM