Russell
Russell

Reputation: 1804

Django ForeignKey filter issue

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

Answers (1)

2ps
2ps

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 filtering 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

Related Questions