Reading multiple entries in a ManyToMany (“through”) table

Let me explain the situation. Let’s assume the example:

class WareHouse():
    name = models.CharField('Name', max_length=100)
    street = models.CharField('Street', max_length=100)
	city = models.CharField('City', max_length=100)

    def __str__(self):
        return self.name


class Product():
    brand = models.CharField('Brand', max_length=100)
    model = models.CharField('Model', max_length=100)
    description = models.CharField('Description', max_length=200)
    warehouse = models.ManyToManyField(WareHouse, through='Storage')

    def __str__(self):
        return f"{self.brand} - {self.model}"


# Tabela ManyToMany
class Storage():
    product = models.ForeignKey('produtos.Produto', verbose_name='Produto', on_delete=models.CASCADE)
    warehouse = models.ForeignKey('produtos.WareHouse', verbose_name='Armazem', on_delete=models.CASCADE)
    quantity = models.IntegerField('Quantity')

    def __str__(self):
        return f"{self.product} - {self.warehouse} - {self.quantity}"

Forgive my english if I’m using WareHouse and Storage wrong. But the idea is that Products are stored in Warehouses and Storage holds info about quantity of a product in a specific warehouse.
Let’s say I have 2 warehouses, W1 and W2 and Products P1 and P2. I can have P1 and P2 in both warehouses.

Creation of products and warehouses

p1 = Product()
p1.model = 'pen'
p1.brand = 'some brand'
p1.save()

p2 = Product()
p2.model = 'book'
p2.brand = 'some brand'
p2.save()

w1 = WareHouse()
w1.name = 'warehouse1'
w1.save()

w2 = WareHouse()
w2.name = 'warehouse2'
w2.save()

Storing 5 p1 in w1, and 10 p1 in w2

w1_p1 = Storage()
w1_p1.product = p1
w1_p1.warehouse = w1
w1_p1.quantity = 5
w1_p1.save()

w2_p1 = Storage()
w2_p1.product = p1
w2_p1.warehouse = w2
w2_p1.quantity = 10
w2_p1.save()

Storing 7 p2 in w1, and 14 p2 in w2

w1_p2 = Storage()
w1_p2.product = p2
w1_p2.warehouse = w1
w1_p2.quantity = 7
w1_p2.save()

w2_p2 = Storage()
w2_p2.product = p2
w2_p2.warehouse = w2
w2_p2.quantity = 14
w2_p2.save()

If I want to know how many products of ‘some brand’, how can i achieve this?
If I get only one product like bellow, using first, thats fine. temp2 holds the info.

temp1 = Product.objects.filter(brand__icontains='some brand').first()
temp2 = Product.objects.get(pk=temp.id).storage_set.all()

But I want to know the quantity for all products of ‘some brand’

temp3 = Product.objects.filter(brand__icontains='some brand').storage_set.all()

Whitch is wrong. But how can I get this info?

Your Storage model is a model like any other - you can query on it in the same way that you query any other model.

For example, if you want:

Then the query would be something like:
total = Storage.objects.filter(product__brand='some brand').aggregate(quantity=Sum('quantity'))

(Note: I’m winging this and there may be errors here. I suggest you verify this in the Django shell before including it in your view.)