使用Query而不是for循环

时间:2012-01-26 21:09:43

标签: django

有没有办法在django查询的单行中执行以下操作?

providers_with_no_contacts = []
for provider in Provider.objects.all():
    if not provider.userprofile_set.all():
        provider_with_no_contacts.append(provider)

还是比这更好的方式?

providers_with_no_contacts = [provider for provider in Provider.objects.all() 
                               if not provider.userprofile_set.all()]

2 个答案:

答案 0 :(得分:1)

Provider.objects.filter(userprofile__isnull=True)

答案 1 :(得分:0)

providers_with_no_contacts = Provider.objects.filter(userprofile_set=None)