在Django中扁平化多个同名的查询集

3lxsmp7m  于 2023-04-07  发布在  Go
关注(0)|答案(1)|浏览(86)

我有多个查询集,看起来像:

NAME1 | VALUE_FROM_COLUMN_1
NAME1 | VALUE_FROM_COLUMN_2
NAME1 | VALUE_FROM_COLUMN_3

除了使用list(chain(q1, q2, q3))函数之外,我如何使这个设计变平,因为它显示如下:

NAME1 | VALUE_FROM_COLUMN_1  |                      |
NAME1 |                      | VALUE_FROM_COLUMN_2  |
NAME1 |                      |                      | VALUE_FROM_COLUMN_3

我想要这个:

NAME1 | VALUE_FROM_COLUMN_1  | VALUE_FROM_COLUMN_2  | VALUE_FROM_COLUMN_3

正如@Willem货车Onsem建议的那样,我试图在下面详细说明:

list1 = OrderElement.objects.filter(ordel_order_fk_id__in=Order.objects.filter(ord_status=2, ord_data_real__lte=datetime.now() + timedelta(days=7)).
values_list('ord_id', flat=True)).values('ordel_name').annotate(total1=Sum('ordel_ilosc')).order_by()
list2 = OrderElement.objects.filter(ordel_order_fk_id__in=Order.objects.filter(ord_status=2, ord_data_real__lte=datetime.now() + timedelta(days=14), ord_data_real__gte=datetime.now() + timedelta(days=7)).
values_list('ord_id', flat=True)).values('ordel_name').annotate(total2=Sum('ordel_ilosc')).order_by()

基本上我通过他们的父母日期过滤位置。这给了我输出:

list1:
ordel_name: OrderElementName1, total1: 50
...

list2:
ordel_name: OrderElementName1, total2: 100
...

型号:

class Order(models.Model):
    ord_id = models.AutoField(unique=True, primary_key=True)
    ord_data_real = models.DateField()

class OrderElement(models.Model):
    ordel_id = models.AutoField(unique=True, primary_key=True)
    ordel_order_fk = models.ForeignKey(Order, on_delete=models.CASCADE)
    ordel_name = models.CharField(max_length=100, unique=False)
    ordel_qty = models.IntegerField(unique=False)
z8dt9xmd

z8dt9xmd1#

我们可以使用单个查询集:

from django.db.models import Q, Sum

data = (
    OrderElement.objects.filter(
        ordel_order_fk__ord_status=2,
        ordel_order_fk__ord_data_real__lte=datetime.now() + timedelta(days=14),
    )
    .values('ordel_nazwa')
    .annotate(
        total1=Sum(
            'ordel_ilosc',
            filter=Q(
                ordel_order_fk__ord_data_real__lte=datetime.now()
                + timedelta(days=7)
            ),
        ),
        total2=Sum('ordel_ilosc'),
    )
    .order_by('ordel_nazwa')
)

这将使字典与ordel_nazwa作为关键字,和两个额外的关键字total1total2的数量ordel_ilosc的前七天和前14天分别。

相关问题