Rahul Sharma
Rahul Sharma

Reputation: 2495

Extract data from queryset

Models.py

class MasterItems(models.Model):

    owner = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='ShipperItems_owner')
    name = models.CharField(max_length=255, default="", null=True)

    length = models.FloatField(blank=True, null=True)
    breadth = models.FloatField(blank=True, null=True)
    height = models.FloatField(blank=True, null=True)
    weight = models.FloatField(blank=True, null=True)


class SalesOrderItems(models.Model):
    item = models.ForeignKey(MasterItems, on_delete=models.CASCADE)
    item_quantity = models.IntegerField(default=0)


class SalesOrder(models.Model):

    owner = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='so_owner')
    client = models.ForeignKey(MasterClient, on_delete=models.CASCADE, related_name='so_client')
    items = models.ManyToManyField(SalesOrderItems, related_name='items_so', blank=True, null=True)

From the frontend I am receiving pk of sales order for e.g [4,2] and I want to extract the Items associated with these SalesOrder

What I tried:

        items = []

        for i in sales_orders:

            so_items = SalesOrderItems.objects.filter(items_so=i)
            print("so_items ", so_items)

            items.append(so_items)

But the output I get is this:

items = [<QuerySet [<SalesOrderItems: SalesOrderItems object (4)>, <SalesOrderItems: SalesOrderItems object (5)>]>, <QuerySet [<SalesOrderItems: SalesOrderItems object (1)>]>]

How can I get the items weight ? Actually SalesOrderItems has item_quantity and I want to multiply that quantity with the item weight to get the total weight of items

Upvotes: 0

Views: 67

Answers (2)

Davit Tovmasyan
Davit Tovmasyan

Reputation: 3588

Try the following:

Do a single query(optional, it's just an optimization):

queryset = SalesOrderItems.objects.filter(items_so__pk__in=sales_orders)

Then multiply like below:

from django.db.models import FloatField, F, ExpressionWrapper

items = queryset.annotate(total_weight=ExpressionWrapper(
    F('item_quantity') * F('item__weight'), output_field=FloatField())

Each object in queryset will have a new attribute called total_weight and that's the value that you need.

for item in items:
    item.total_weight # this is what you are looking for

Upvotes: 1

Wariored
Wariored

Reputation: 1343

You can use values method and include inside columns you want to use

items =[]
for i in sales_orders:
  so_items = SalesOrderItems.objects.filter (items_so = i).values(
        'item__name',
        'item_quantity'
    )
  print ("so_items ", so_items) items.append (so_items)

Upvotes: 0

Related Questions