简体   繁体   English

在 django orm 查询中使用 model 方法

[英]using model method in the django orm query

I have a model which has the model method called cancelled_date which returns date when a record from the models is cancelled how can i access this method in my query set to get the particular data.我有一个 model,它有一个名为 cancelled_date 的 model 方法,它返回取消模型中的记录时的日期如何在我的查询集中访问此方法以获取特定数据。

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

the function cancellation date returns the date the day record is cancelled function 取消日期返回当天记录被取消的日期

i want to filter the Cancellation date from Record model and do smething我想从记录 model 中过滤取消日期并做一些事情

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

I am able to access in like this but is there a way that i could filter only records cancellation_date which are set to today's date我可以像这样访问,但是有没有一种方法可以只过滤设置为今天日期的记录 cancel_date

You cannot use methods defined in the Model class, inside the .filter() .您不能在.filter()中使用 Model class 中定义的方法。

You can use annotation instead:您可以改用注释:

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