M
M
Maxim Zubenko2021-11-16 19:19:26
Django
Maxim Zubenko, 2021-11-16 19:19:26

Django: How to find out in a category the number of brands of products in this category?

Available models:

class Brand(models.Model):
    title = models.CharField(max_length=100, verbose_name="Название")

class Category(models.Model):
    title = models.CharField(max_length=100, verbose_name="Название")

class Product(models.Model):
    category = models.ForeignKey(Category, on_delete=models.PROTECT, verbose_name='Категория')
    brand = models.ForeignKey(Brand, on_delete=models.PROTECT, default=1, verbose_name='Бренд')
    title = models.CharField(max_length=100, verbose_name='Название')


I create two brands. I create a couple of categories. In one category, products from one brand. In another category - products from different brands.

The user enters the directory and selects category 1. it contains products from the same brand, then he immediately receives a list of products, i.e. it will immediately be redirected to the category_detail.html template

. Also, the user enters the catalog and selects category 2. And since. there are products of different brands in it, then he is sent to another template, where he must first select a brand, i.e. he slipped the category_brands.html template

Question 1. How to catch this moment? (well, that is, how to find out in the view before the template how many brands the products have in the selected category)

Question 2: The customer also wants a similar moment in the admin panel on the category page with a list of products (i.e. if there is one brand, then remove the column with brands in the table altogether, and if products, brands have more than 1, then write the brand name )

ps Did something similar once (on the second question). I remember that something with Count and annotate can be stirred up, but I can’t find the details. Guys help, it's spinning in my head, but in fact I did this:
def category_list(request):
    list_ = Category.objects.annotate(brand_count=Count('product__brand'))

But it counts the number of products, not brands.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question