Django query where in

kelvinfix picture kelvinfix · May 10, 2011 · Viewed 39.5k times · Source

How to do this using django object query:

 SELECT * FROM test WHERE (test_id IN (SELECT test_id FROM test_subject_set)) AND (test_begin_time < '') AND (test_end_time > '')

The model:

class Test(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User)
    groups = models.ManyToManyField(Group)


class TestSubjectSet(models.Model):
    id =  models.AutoField(primary_key=True)
    test = models.ForeignKey(Test)

Answer

DrTyrsa picture DrTyrsa · May 10, 2011

Two querysets is documented way of doing this. It will be one database hit anyway.

test_ids = Subject.objects.all()
result = Test.objects.filter(test_id__in=test_ids).filter([some other filtering])