Nerd
Nerd

Reputation: 275

Brand Filter by Category in shopping django rest

I am facing problems on filtering Brand by Category in Django Rest Framework.

class Category(TimeStamp):
    name = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True, blank=True)
    icon = models.ImageField(upload_to='category_icons', null=True, blank=True)
    parent = models.ForeignKey('self', on_delete=models.SET_NULL, related_name='children', null=True, blank=True)



class Brand(models.Model):
    brand_name = models.CharField(max_length=150)
    brand_image = models.ImageField(upload_to='brand_images', null=True, blank=True)
    category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, null=True)

here I have two models. For example I have a Category like Clothing -> Foot Wear -> Shoes if user enter Clothing category I should get all brands in Clothing but when I go to Shoes section I should get all brands in Shoes category. For this How can I write query_set? Any help would appreciated! Thanks in advance!

Upvotes: 0

Views: 179

Answers (1)

waranlogesh
waranlogesh

Reputation: 1024

Add a related name to category foreign key

category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, null=True, related_name="brands")

Then

clothing_category = Category.objects.get(name="Clothing")
clothing_brands = clothing_category.brands.all()

shoe_category = Category.objects.get(name="Shoes")
shoe_brands = shoe_category.brands.all()

Upvotes: 1

Related Questions