'How to merge two dependant models in django and get count of each type

I'm new to django, how to relate two model classes and extract total count of it

class FoodBatch(models.Model):
    batch_code = models.CharField(max_length=200, blank=False, null=False)
    expiry = models.DateField()
    price = models.FloatField()

class FoodItem(models.Model):
    seller_code = models.CharField(max_length=200, blank=False, null=False)
    brand = models.CharField(max_length=200, blank=False, null=False)
    quantity = models.IntegerField()
    batch = models.ManytoMany(FoodBatch)

FoodBatch has to be unique for each FoodItem. FoodItem can map to multiple FoodBatch.

Also, need to total count of quantity from all the FoodBatch for each FoodItem.

Thanks in advance.



Solution 1:[1]

I don't know what you want to do!!

But this is steps to explain your code:

1- must be change :

batch = models.ManytoMany(FoodBatch)

to this code:

batch = models.ManyToManyField(FoodBatch)

2- create dump data for testing:

fb1 = FoodBatch(batch_code = "100",expiry ="2022-02-02",price = 100)
fb1.save()

fb2 = FoodBatch(batch_code = "200",expiry ="2022-02-02",price = 200)
fb2.save()

fb3 = FoodBatch(batch_code = "300",expiry ="2022-02-02",price = 300)
fb3.save()

# create FoodItem instance and set tow FoodBatch instances only for it.
fi1 = FoodItem(seller_code="111",brand="A",quantity=10)
fi1.save()
fi1.batch.set([fb1,fb2])

# to extra total count:

FoodBatch.objects.annotate(item_total = models.Sum('fooditem__quantity')).values()

# result like these:

<QuerySet [

{'id': 1, 'batch_code': '100', 'expiry': datetime.date(2022, 2, 2), 'price': 100.0, 'item_total': 10},

{'id': 2, 'batch_code': '200', 'expiry': datetime.date(2022, 2, 2), 'price': 200.0, 'item_total': 10},

{'id': 3, 'batch_code': '300', 'expiry': datetime.date(2022, 2, 2), 'price': 300.0, 'item_total': None}]>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eng.Faris Alsmawi