Python 使用自动计算的属性字段进行 Django 过滤查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31658793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django filter query on with property fields automatically calculated
提问by bobsr
There is Django Order model with property fields automatically calucated. How to do a filter query.
有自动计算属性字段的 Django Order 模型。如何进行过滤查询。
class Order(models.Model):
@property
def expire(self):
return self.created + datetime.timedelta(days=self.days_left())
@property
def days_left(self):
return self.recurrence_period * self._recurrence_unit_days[self.recurrence_unit]
Calculation done to get 1,3,7 datetime days from today
从今天开始计算得到 1,3,7 个日期时间
settings.SUBSCRIPTION_EXPIRATION_REMIND = [1, 3, 7]
days = map(lambda x: datetime.date.today() + datetime.timedelta(days=x), settings.SUBSCRIPTION_EXPIRATION_REMIND)
[datetime.date(2015, 7, 28),
datetime.date(2015, 7, 30),
datetime.date(2015, 8, 3)]
How to filter by ORM query
如何按 ORM 查询过滤
Order.objects.filter(expire__in=days)
Django is throwing error.
Django 抛出错误。
FieldError: Cannot resolve keyword 'expire' into field.
采纳答案by bobsr
Ended up adding expire to model, calculating the value on save method. Now i can do
最终将过期添加到模型中,计算保存方法的值。现在我可以
Order.objects.filter(expire__in=days)
回答by Shaikhul
I dont think you can use a property in the field lookups as the doc says The field specified in a lookup has to be the name of a model field
https://docs.djangoproject.com/en/1.8/topics/db/queries/#field-lookups
我认为您不能像文档所说的那样在字段查找中使用属性The field specified in a lookup has to be the name of a model field
https://docs.djangoproject.com/en/1.8/topics/db/queries/#field-lookups
回答by Rahul Gupta
No, you can't perform lookup based on model methods or properties. Django ORM does not allow that.
不,您不能根据模型方法或属性执行查找。Django ORM 不允许这样做。
Queries are compiled to SQL to be sent and processed at the database level whereas properties are Python code and the database knows nothing about them. That's the reason why the Django filter only allows us to use database fields.
查询被编译为 SQL 以在数据库级别发送和处理,而属性是 Python 代码,数据库对它们一无所知。这就是为什么 Django 过滤器只允许我们使用数据库字段的原因。
Can do this:
可以这样做:
Order.objects.filter(created=..) # valid as 'created' is a model field
Cannot do this:
不能这样做:
Order.objects.filter(expires=..) # INVALID as 'expires' is a model property
You can instead use list comprehensions to get the desired result.
您可以改为使用列表推导式来获得所需的结果。
[obj for obj in Order.objects.all() if obj.expire in days]
The above will give me the list of Order
objects having expire
value in the days
list.
以上将为我提供列表中Order
具有expire
价值的对象days
列表。