Django query where in

2019-03-10 01:25发布

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)

3条回答
乱世女痞
2楼-- · 2019-03-10 02:01

DrTyrsa just about had it.

test_ids = list(TestSubjectSet.objects.all().values_list('test_id', flat=True))
result = Test.objects.filter(id__in=test_ids, test_begin_time__lt='', test_end_time__gt='')

The way Tyrsa was doing it would not give you a list of the Test ids from TestSubjectSet, but instead give you a TestSubjectSet queryset.

Also, I was confused by the test_begin_time and test_end_time fields, because you didn't mention them in your models.

Update: Used list() on the queryset, because, according to the link DrTyrsa posted, DBs "don't optimize nested querysets very well".

查看更多
\"骚年 ilove
3楼-- · 2019-03-10 02:01

this worker for me:

Line.objects.filter(pk__in=[1, 2, 3])
查看更多
Lonely孤独者°
4楼-- · 2019-03-10 02:23

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])
查看更多
登录 后发表回答