我如何在Django中执行此查询?

时间:2011-04-06 08:00:47

标签: python mysql database django

class ExternalUser(models.Model):
    user = models.ForeignKey(User)
    external_account_id = models.CharField(max_length=200, null=True, blank=True)

class ExternalFriends(models.Model):
    external_user = models.ForeignKey(ExternalUser)
    external_account_id = models.CharField(max_length=200, null=True, blank=True)

假设我首先获得所有ExternalFriends:

all_friends = ExternalFriends.objects.all()

好的,现在我有一个查询集。

我如何SELECT * FROM ExternalUser WHERE external_account_id IN [ ...all_friends's external_account_ids... ]

Django的等价物是什么?

1 个答案:

答案 0 :(得分:1)

当然可以更有效地完成,但......

ExternalUser.objects.filter(external_account_id__in=[friend.id for friend in all_friends])