Django query where in

后端 未结 3 1458
温柔的废话
温柔的废话 2021-01-31 17:02

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         


        
3条回答
  •  别跟我提以往
    2021-01-31 17:37

    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".

提交回复
热议问题