如何在django中查找父对象父级的所有多对象

时间:2013-08-20 18:48:36

标签: django django-models django-orm

我有以下对象结构:

class Customer(models.Model):
    name = models.CharField('Customer Name', max_length=64)

class Location(models.Model):
    customer = models.ForeignKey(Customer)
    groups = models.ManyToManyField(Group, blank=True, null=True)

class Group(models.Model):
    name = models.CharField('Group Name', max_length=64)

如何为客户找到所有唯一的Group对象?

1 个答案:

答案 0 :(得分:2)

对于customer对象,

groups = Group.objects.filter(location__customer = customer).distinct()

lookups across relationships

上的文档