[英]How to perform a double step Subqueries in Django?
I have the below models: 我有以下型号:
class Group(models.Model):
group_name = models.CharField(max_length=32)
class Ledger(models.Model):
ledger_name = models.CharField(max_length=32)
group_name = models.ForeignKey(Group,on_delete=models.CASCADE,null=True,related_name='ledgergroups')
class Journal(models.Model):
By = models.ForeignKey(Ledger,on_delete=models.CASCADE,related_name='Debitledgers')
To = models.ForeignKey(Ledger,on_delete=models.CASCADE,related_name='Creditledgers')
Debit = models.DecimalField(max_digits=20,decimal_places=2,default=0)
Credit = models.DecimalField(max_digits=20,decimal_places=2,default=0)
As you can see the Journal
model is related with the Ledger
models with a Foreignkey
relation which is further related with Group
model. 如您所见,
Journal
模型与带有外Foreignkey
关系的Ledger
模型相关, Foreignkey
关系又与Group
模型相关。
My scenario is kind of complex. 我的情况有点复杂。
I want to filter the Group
objects and their balances ( Balances are the difference between their total Debit
and their total Credit
). 我想过滤
Group
对象及其余额( 余额是其总Debit
与总Credit
之间的差 )。
I want to filter the total Group names and the subtraction of total Debit
and total Credit
..( Debit
and Credit
are the fields of Journal
model ). 我想过滤总的组名称,并减去总
Debit
和总Credit
..( Debit
和Credit
是Journal
模型的字段 )。
Can anyone help me to figure out the above. 谁能帮我解决以上问题。
I have tried Subqueries
before in Django
but haven't done a two step Subquery
in Django
. 我曾尝试
Subqueries
之前Django
,但还没有做两步Subquery
中Django
。
Any solution will be helpful. 任何解决方案都会有所帮助。
Thank you 谢谢
You can use annotations to calculate sums, averages, counts, etc. These annotations can then be used to filter on 您可以使用批注来计算总和,平均值,计数等。然后可以使用这些批注对
from django.db.models import Sum, F
groups_with_negative_balance = Group.objects.annotate(
total_debt=Sum('ledgergroups__Debitledgers__Debit'),
total_credit=Sum('ledgergroups__Creditledgers__Credit'),
).annotate(
balance=F('total_credit') - F('total_debt')
).filter(
balance__lt=0
)
try this 尝试这个
from django.db.models import Subquery
>>> users = User.objects.all()
>>> UserParent.objects.filter(user_id__in=Subquery(users.values('id')))
<QuerySet [<UserParent: UserParent object (2)>, <UserParent: UserParent object (5)>, <UserParent: UserParent object (8)>]>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.