I have 2 classes of the model and I need to get the number of products from each of the suppliers

class Vendor(models.Model): name = models.CharField(max_length=50, unique=True) seo_name = models.SlugField() product_count = models.IntegerField(default=0) class Product(models.Model): vendor = models.ForeignKey(Vendor, unique=False, blank=True, default=None, null=True, on_delete=models.SET_NULL) 

How to do it?

    1 answer 1

    For a specific supplier like this:

     Product.objects.filter(vendor=vendor).count() 

    Documentation about count () .

    If for all suppliers, something like this:

     Product.objects.all().values('vendor').annotate(total=Count('vendor')) 

    values group, and Count count. A similar question in English Stekoferflow .

    • in this way it will not be possible to write the number of objects in the field in Vendor, I solved the problem with signals, like this: toster.ru/q/318583 - Alexandr Domoryonok