简体   繁体   English

带变量的Django ORM复合过滤器

[英]Django ORM compound filter with variables

I'm by no means a Django expert, and need some guidance on a problem. 我绝不是Django专家,并且需要有关问题的一些指导。

For background, I have a older .NET project that I've been tasked to turn into Django project. 作为背景,我有一个较旧的.NET项目,我已被委派为Django项目。 The project gets a full list of objects and then runs a large set of user set filters to end up with the desired set of objects. 该项目将获取对象的完整列表,然后运行大量用户设置的过滤器以最终获得所需的对象集。

One of the filters in .NET might be like so ... .NET中的筛选器之一可能像这样...

matched.RemoveAll(x => ((x.annualIncome / 12) - x.payment) < monthlyIncome);

I'm trying to figure out how I would do this with the django ORM. 我试图弄清楚如何用django ORM做到这一点。 I'm kind off stuck on this. 我有点坚持。

In a pseudo-code django ORM version (yes, this will not work): 在django ORM伪代码版本中(是的,这不起作用):

matched.exclude(((annualIncome /12)-payment)__gt = monthlyIncome)

There are 30+ filters before this one so I can't re-do them all in a different manner. 在此之前有30多个过滤器,因此我无法以不同的方式重新进行过滤。 I can obviously go through each object and filter but I decided to ask first. 我显然可以遍历每个对象并进行过滤,但是我决定先问一下。

I'm open to solutions here or friendly "RTFM, this pages answers it." 我对这里的解决方案或友好的“ RTFM,此页已回答”很开放。

Thanks in advance, and mods please edit with a better title as my brain is now officially fried from 3 days coding with the Flu. 在此先感谢您,mod的名称也应进行修改,因为我的大脑现在已经开始用流感编码3天,因此正式被炒了。

In that case welcome to the magical world of Django ORM (and not in a bad sense, it's actually pretty reasonable most of the time :). 在那种情况下,欢迎来到Django ORM的魔幻世界(而且从某种意义上讲,在大多数情况下,这实际上是相当合理的:)。

from django.db.models import F, Case

# Your stuff
matches.annotate(
    req=Case(default=(F('annualIncome') / 12) - F('payment'))
).exclude(req__gt=monthlyIncome)

Because you can't query directly in that kind of a calculation, then the F object tells ORM that this should come from the database, go and get it. 因为您不能直接通过这种计算进行查询,所以F对象告诉ORM,它应该来自数据库,然后获取它。
Untested (due to lack of similar case in my projects), but if problems arise, do let me know. 未经测试(由于我的项目中缺少类似案例),但是如果出现问题,请告诉我。

PS. PS。 You can change the req name to whatever you like. 您可以将req名称更改为任何您喜欢的名称。

EDIT: 编辑:
Wow, this is awkward. 哇,这很尴尬。 You can just do it without the Case as well. 您也可以不使用Case

matches.annotate(req=(F('annualIncome') / 12) - F('payment')).exclude(req__gt=monthlyIncome)

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

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