3

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
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
Russell
  • 1,624
  • 5
  • 23
  • 43

1 Answers1

3

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)
2ps
  • 15,099
  • 2
  • 27
  • 47
  • I'm using `group = models.ForeignKey(Category.objects.filter(group__category__name="foo"))` but got error `django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.` – Russell Dec 26 '16 at 06:39
  • This means you aren’t using django with the standard manage.py. If that is the case: http://stackoverflow.com/questions/24793351/django-appregistrynotready – 2ps Dec 26 '16 at 13:55