M
M
Maxim Zubenko2018-09-17 12:21:08
Django
Maxim Zubenko, 2018-09-17 12:21:08

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

Introductory 1 :
There are many categories. Each of them contains a group of goods. From 0 to 100. This means that some categories are empty because there are no products in them.
Question : How in views.py to execute a request for a list of categories, only those in which there are products. Insert some tricky count > 0 somewhere in the filter. I understand that this is a complex SQL query, but is there such a possibility with Django or not? Or it may be necessary to make several requests, but then how? (write the code please).
Introductory 2 : Everything is the same. Only in the Products model there is also a quantity Question 2
qty = models.IntegerField(default=0)
: How in views.py to execute a request (requests) for a list of categories, only those in which there are those products whose number is greater than 0. Is it possible to implement this using simple Django tools or not? Or it may be necessary to make several requests, but then how? (write the code please).
ps The resulting list will be passed through context to the template and used in for. Both model values ​​(category.title and category.slug) will be needed.
ps2. My slug is filled in automatically if it doesn't exist, so there is blank=True (in general, don't bother and don't get distracted by this)
Regards!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Zubenko, 2018-09-23
@JawsIk

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 question

Ask a Question

731 491 924 answers to any question