RoverDar RoverDar - 1 year ago 149
Python Question

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?

Answer Source
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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download