RoverDar
RoverDar

Reputation: 441

Django queryset filter from two models

In my Django app I have two model and I don't know how to do a query for select the right record. This is the code:

class tab1 (models.Model):
    id_tab1 = models.AutoField(primary_key=True)
    name = models.CharField(max_length=50)

class tab2 (models.Model):
    id_tab1 = models.ForeignKey(tab1)
    type = models.IntegerField()

I would like to select the tab1 records that have tab2.type equal to some condition. How can I do this in Django?

Upvotes: 2

Views: 8531

Answers (2)

Pynchia
Pynchia

Reputation: 11606

your_queryset = tab1.objects.filter(tab2__type=value)

See the relevant documentation here In a few words: you can span relationships either way (i.e. from each end of a foreign key). The condition is specified in the named argument to filter(). The one I suggested above is the simplest one (i.e. equality), but there are quite a few more (e.g. startswith, contains, etc). Please read here

Upvotes: 4

Kantha Girish
Kantha Girish

Reputation: 67

Consider you have values 1,2 stored for the field type. The following illustrates the one way of achieving your need for type=1.

filtered_objs = tab1.objects.filter(type=1)
tab2.objects.filter( tab1__in=filtered_objs)

Upvotes: 0

Related Questions