leonking93
leonking93

Reputation: 39

How do I write a queryset to display all products linked to a category?

I am new to Django and am trying to display my products on a page that are linked to a certain category.

I have tried codes such as queryset = Product.objects.filter(category__exact='Badges')

Here are my models.

class ProductCategory(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField()
    parent = models.ForeignKey('self', blank=True, null=True,
                related_name='children', on_delete=models.PROTECT)

class Product(models.Model):
    title       = models.CharField(max_length=100)
    category    = models.ForeignKey(ProductCategory, null=True, blank=True,
                    on_delete=models.CASCADE)
    slug        = models.SlugField(blank=True)
    description = models.TextField()
    price       = models.DecimalField(decimal_places=2, max_digits=6)
    image       = models.ImageField(upload_to='products/', null=True, blank=True)

I am expecting to get the objects in products that are linked to a certain category to print.

Upvotes: 1

Views: 423

Answers (2)

Tanvir Islam Streame
Tanvir Islam Streame

Reputation: 460

First get the instance from the "ProductCategory" , then get it from "Product"

instance = ProductCategory.objects.get(title__iexact='Badges')
Product.objects.get(category=instance)

Upvotes: 3

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476669

If you have a ProductCategory object, you can filter with:

Product.objects.filter(category=my_category)

It appears however that you aim to filter on the title (with a string), then you can filter with:

Product.objects.filter(category__title='Badges')

or for the slug:

Product.objects.filter(category__slug='Badges')

Upvotes: 3

Related Questions