Reputation: 1804
Is there anyway to add filter on django foreignkey field.
class Product(models.Model):
name = models.CharField(max_length=100)
category = models.ForeignKey(Category)
image = models.ImageField()
description = models.TextField()
def __str__(self):
return self.name
Upvotes: 3
Views: 169
Reputation: 15926
Yes. You can just use the key__
syntax like this:
products = Product.objects.filter(category__name='Tops')
Just make sure what is after the __
appears in the Category
model and you will be good to go. You can read more about how django handles cross-relationship filter
ing here.
You can also just query by the related ID itself:
category = Category.objects.get(id=25)
products = Producct.objects.filter(category_id=25)
Upvotes: 3