Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django从相关表查询和值_Django_Django Queryset - Fatal编程技术网

Django从相关表查询和值

Django从相关表查询和值,django,django-queryset,Django,Django Queryset,我有两张桌子: 售票处 id paid_with_tax 1 5 2 6 3 7 票证调整表 id ticket_id value_with_tax 1 1 2 2 1 1 3 1 2 4 1 3 5 2 5 我使用的查询: use = 0 Ticket.objects.all().annotate( paid_amount=Sum( F('

我有两张桌子:

售票处

id  paid_with_tax
1   5
2   6
3   7
票证调整表

id  ticket_id  value_with_tax
1   1          2
2   1          1
3   1          2
4   1          3
5   2          5
我使用的查询:

use = 0

Ticket.objects.all().annotate(
   paid_amount=Sum(
        F('paid_with_tax') +
        Coalesce(F('ticketadjustment__value_with_tax'), 0) * use
    )
)
查询将返回以下内容:

[
    {id: 1, paid_amount: 7},
    {id: 1, paid_amount: 6},
    {id: 1, paid_amount: 7},
    {id: 1, paid_amount: 8},
    {id: 2, paid_amount: 11},
    {id: 3, paid_amount: 7},
]
[
    {id: 1, paid_amount: 13},
    {id: 2, paid_amount: 11},
    {id: 3, paid_amount: 7},
]
但上述内容不正确,因为票证表id=1的值与票证调整表的值重复

如何使查询对TicketAdjustment表的值求和并返回以下值:

[
    {id: 1, paid_amount: 7},
    {id: 1, paid_amount: 6},
    {id: 1, paid_amount: 7},
    {id: 1, paid_amount: 8},
    {id: 2, paid_amount: 11},
    {id: 3, paid_amount: 7},
]
[
    {id: 1, paid_amount: 13},
    {id: 2, paid_amount: 11},
    {id: 3, paid_amount: 7},
]

以下是您问题的解决方案:

Ticket.objects.all().annotate(
   paid_amount=(F('paid_with_tax') +
        Sum(Coalesce(F('ticketadjustment__value_with_tax'), 0))
    )
).values_list('id', 'paid_amount')
值\u列表
选择结果中所需的字段

在您的主要请求中存在一个大问题

Sum(F('paid_with_tax') + Coalesce(F('ticketadjustment__value_with_tax'), 0) * use)
这条直线的最小值为零。所以给你零分。就像:

Sum(F('paid_with_tax'))
您需要每张票的
value\u和\u tax
之和,这就是为什么我在上面移动
sum

Sum(Coalesce(F('ticketadjustment__value_with_tax'), 0)) 
加上
已缴纳税费的价值后

注意:我删除了变量
use
,因为我不知道目标是什么