我如何在Django中组合这些查询?

时间:2013-07-09 04:01:04

标签: django django-models django-queryset

所以我有一些像这样的代码:

objects_list = A.objects.filter(some_param = some_value)

for obj in objects_list:
    object = B.objects.get(pk=obj.another_param)
    #do stuff with the B object

有没有办法将它组合成一个查询或什么?怎么样?谢谢!

1 个答案:

答案 0 :(得分:0)

你可以这样做:

a_qs = A.objects.filter(some_param=some_value).values_list('another_param', flat=True)
b_qs = B.objects.filter(pk__in=a_qs)

for b in b_qs:
    #do stuff with b

或者,如果你想巩固:

b_qs = B.objects.filter(pk__in=A.objects.filter(some_param=some_value).values_list('another_param', flat=True))

for b in b_qs:
    #do stuff with b