Как я могу получить бренды на основе определенной категории в django?

Я могу получить все продукты на основе определенного имени категории и бренда, но я не могу получить бренды на основе определенного имени категории. Как я могу это сделать?

Моя модель категории

class Category(models.Model):
    category_name = models.CharField(max_length=20, unique=True)
    logo = models.ImageField(upload_to='Category')
    slug = models.SlugField(unique="True", help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents")

    def __str__(self):
        return self.category_name

Моя модель бренда


class Brand(models.Model):
    brand_name = models.CharField(max_length=40, null=True, blank=True, unique=True)

    def __str__(self):
        return self.brand_name

Моя модель продукта

class Product(models.Model):
    product_name = models.CharField(max_length=50, blank=False, help_text='Add Product Model Name or Product Name.')
    category = models.ForeignKey(Category, on_delete=models.CASCADE, default="", blank=True, related_name="Products")
    brand_name = models.ForeignKey(Brand, on_delete=models.CASCADE, default="", blank=True, related_name="Products")
    specification = models.CharField(max_length=400, blank=True, default="")
    price = models.FloatField(blank=False, default=0.00, validators=[MinValueValidator(0.0)], help_text='Price Can not be Less than Zero.')
    quantity = models.PositiveBigIntegerField(default=0)

    class Meta:
        unique_together = [['category', 'brand_name', 'product_name', 'specification'] ]
    
    def __str__(self):
        return self.product_name

На основе ваших моделей это должно быть что-то вроде:

brand_names = Product.objects.filter(category__category_name="some_name").values_list("brand_name__brand_name", flat=True)

или если под brand_name вы подразумеваете экземпляры модели Brand, то

brand_names = Product.objects.filter(category__category_name="some_name").brand_name.all()

(BTW Я бы рассмотрел возможность переименования полей в ваших моделях. В модели Product переименуйте brand_name в просто brand, а в модели Brand переименуйте поле brand_name в просто name. То же самое для Категории. Так будет гораздо меньше путаницы)

Вы можете .filter(…) [Django-doc] с:

Brand.objects.filter(Products__category=my_category).distinct()

или для имени категории:

Brand.objects.filter(
    Products__category__category_name=my_category_name
).distinct()

вызов .distinct() [Django-doc]. предотвращает возврат одного и того же Brand несколько раз.


Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase. Since the value for the related_name=… parameter [Django-doc] specifies the name of a field that will be defined on the target model, the value of the related_name=… parameter should be written in snake_case as well, so it should be: products instead of Products.


Note: Your Product model acts as a junction table for a many-to-many relation between Category and Brand. You can span a ManyToManyField [Django-doc] on the Category model with:

class Category(models.Model):
    # …
    brands = models.ManyToManyField(
        Brand,
        through='Product'
    )
Вернуться на верх