Django и python, как получить аннотацию от двух разных моделей? - PullRequest
1 голос
/ 13 июля 2020

У меня есть следующая структура модели:

class Subcategory(models.Model):
    nome=models.CharField()

class Order(models.Model):
    order=models.CharField()

class Quantity(models.Model):
    order=models.ForeignKey(Order)
    subcategory=models.ForeignKey(Subcategory)
    quantity=models.DecimalField()

class Price(models.Model):
    order=models.ForeignKey(Order)
    subcategory=models.ForeignKey(Subcategory)
    price=models.DecimalField()

Теперь я хочу получить новое значение, которое дает мне возможность фильтровать subcategory и order для price и quantity queryset и дайте мне их размножение. это код, который я установил, но я не знаю, как получить операцию price*quantity.

cod='1234'
price=dict()
defaults=list(0 for m in range(1))
filter_quantity = list(Quantity.objects.values_list('subcategory__id', flat=True).distinct()).filter(order__order=cod)
    
    for subcategory__id, totals in(Price.objects.filter(
        subcategoty__in=filter_quantity ).values_list('subcategory__id').annotate(totals=ExpressionWrapper(Sum(F('price')),
                output_field=FloatField())).values_list('subcategory__id', 'totals'):
                if subcategory__id not in price.keys():
                    price[subcategory__id ]=list(defaults)
                index=0
                price[subcategory__id][index]=totals
total_costs={'Costs': [sum(t) for t in zip(*price.values())]}

1 Ответ

1 голос
/ 14 июля 2020

Вы также можете внести изменения в этот метод по своему усмотрению.

def get_order_details(order_code):
    order_details = []
    quantities = Quantity.objects.filter(order__order=order_code)
    prices_queryset = Price.objects.filter(order__order=order_code)

    for quantity in quantities:
        price = prices_queryset.filter(order__order=order_code, subcategory=quantity.subcategory).first()
        if price:
            order_details.append({
                'subcategory_name': quantity.subcategory.nome,
                'quantity': quantity.quantity,
                'unit_price': price.price,
                'total_price': quantity.quantity * price.price
            })

    return {
        'order_code': order_code,
        'details': order_details
    }
...