如何使用F()对象来使用Django ORM? [英] How can I use the F() object to do this with the Django ORM?

查看:134
本文介绍了如何使用F()对象来使用Django ORM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这样的模式:

class Task(models.Model):
    timespan = models.IntegerField(null=True, blank=True)

class Todo(models.Model):
    limitdate = models.DateTimeField(null=True, blank=True)
    task = models.ForeignKey(Task)

我需要提取所有的 Todos 一个 limitdate ,低于或等于今天的日期+在相关的任务模型中定义的时间范围

I need to extract all Todos with a limitdate that is lower or equal to today's date + a timespan defined in the related Task model.

某些东西(虚拟示例):

Something like (dummy example):

today = datetime.datetime.now()
Todo.objects.filter(limitdate__lte=today + F('task__timespan'))

现在,我可以用循环来做,但是我正在寻找一种方法来使用 F(),而我找不到一个。

Now, I can do that with a loop but I'm looking for a way to do it with F(), and I can't find one.

我开始怀疑我是否可以用 F()来做到这一点。也许我应该使用额外的

I'm starting to wonder if I can do that with F(). Maybe I should use extra ?

请注意,我没有更改模型代码的奢侈。

Please note that I don't have the luxury of changing the model code.

推荐答案

问题是数据库中没有TIMESPAN类型。所以, F 不能在这个上下文中返回一些你可以实际工作的东西。我不知道你在数据库中实际使用了哪种类型的字段,但是我可以想到的唯一方法就是将时间段存储为一个整数,它由秒组成,并将其添加到today作为时间戳,然后将其转换为datetime,您可以使用它与 limitdate 进行比较。但是,我不确定Django是否会接受这样复杂的逻辑,而 F

The problem is that there's no TIMESPAN type on a database. So, F cannot return something that you can actually work with in this context. I'm not sure what type of field you actually used in your database, but the only way I can think of to do this is to the store the timespan as an integer consisting of seconds, add that to "today" as a timestamp, and then convert it back into a datetime which you can use to compare with limitdate. However, I'm unsure if Django will accept such complex logic with F.

这篇关于如何使用F()对象来使用Django ORM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆