Say I have a model that looks like:
说我的模型看起来像:
class StockRequest(models.Model):
amount_requested = models.PositiveIntegerField(null=True)
amount_approved = models.PositiveIntegerField(null=True)
Is there any way to make a django query that would show me all requests where there is some relationship between amount_requested and amount_approved on a particular object/row?
有没有办法制作一个django查询,它会向我显示特定对象/行上的amount_requested和amount_approved之间存在某种关系的所有请求?
In SQL it would be as simple as:
在SQL中,它将如下所示:
select * from stockrequest where amount_requested = amount_approved;
or
要么
select * from stockrequest where amount_requested = amount_approved;
In Django, I'm not sure if it can be done, but I would imagine something like the below (NOTE: syntax completely made up and does not work).
在Django中,我不确定它是否可以完成,但我会想象下面的内容(注意:语法完全组成并且不起作用)。
StockRequest.objects.filter(amount_requested="__amount_approved")
3 个解决方案
#1
12
from django.db.models import F
StockRequest.objects.filter(amount_requested=F("amount_approved"))
http://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model
http://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model
#2
2
Yes, you can. You can use the built in "F" object to do this.
是的你可以。您可以使用内置的“F”对象来执行此操作。
The syntax would be:
语法是:
from django.db.models import F
StockRequest.objects.filter(amount_requested=F("amount_approved"))
or
要么
StockRequest.objects.filter(amount_requested__gt=F("amount_approved"))
Note: I found the answer immediately after I finished writing the question up. Since I hadn't seen this on Stack Overflow anywhere, I am leaving it up with this answer.
注意:我在写完问题后立即找到答案。由于我没有在任何地方看到Stack Overflow,我将这个答案留给我。
#1
12
from django.db.models import F
StockRequest.objects.filter(amount_requested=F("amount_approved"))
http://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model
http://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model
#2
2
Yes, you can. You can use the built in "F" object to do this.
是的你可以。您可以使用内置的“F”对象来执行此操作。
The syntax would be:
语法是:
from django.db.models import F
StockRequest.objects.filter(amount_requested=F("amount_approved"))
or
要么
StockRequest.objects.filter(amount_requested__gt=F("amount_approved"))
Note: I found the answer immediately after I finished writing the question up. Since I hadn't seen this on Stack Overflow anywhere, I am leaving it up with this answer.
注意:我在写完问题后立即找到答案。由于我没有在任何地方看到Stack Overflow,我将这个答案留给我。