Answer the question
In order to leave comments, you need to log in
Django: How to list only categories where a product is present?
All good health.
There are two models:
class Category(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(blank=True)
def __str__(self):
return self.name
class Product(models.Model):
category = models.ForeignKey(Category, on_delete=models.PROTECT)
title = models.CharField(max_length=120)
slug = models.SlugField(blank=True)
description = models.TextField()
price = models.DecimalField(max_digits=9, decimal_places=2)
available = models.BooleanField(default=True)
def __str__(self):
return self.title
qty = models.IntegerField(default=0)
Answer the question
In order to leave comments, you need to log in
I'm posting my own comment here. Method via annotate .
1. In the Product model, change the line so that the related_name parameter appears:
2. In views.py, import the Count module:
3. Execute the query like this:
The result is similar. Speed and load between methods have not been compared or tested.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question