Django获取ManyToMany关系的对象和关系字段

时间:2016-12-01 17:15:02

标签: python django django-models

我想知道是否可以使用单个查询完成此操作

我的models.py有一个自己有M2M的模型

class Person(models.Model):
    objectid = models.AutoField(primary_key=True)
    name = models.CharField()
    relations = models.ManyToManyField(
        self, 
        on_delete = models.CASCADE, 
        through = Person_Person, #This lets you define the model that will act as an intermadiary
        symmetrical = False, #This needs to be set with recursive relationships
    )

class Person_Person(models.Model):
    cod_person_1 = models.ForeignKey('Person', on_delete=models.CASCADE, related_name='%(class)s_cod_person_1')
    cod_person_2 = models.ForeignKey('Person', on_delete=models.CASCADE, related_name='%(class)s_cod_person_2')
    relation = models.IntegerField(choices =             
        ((0, 'Parent'),
        (1, 'Child'),
        (2, 'Engaged'),
        (3, 'Widow'),
        (4, 'Related')),
    default = 4)

然后我将此功能添加到Person模型以获取所有相关的Person

class Person(models.Model):
    ...
    def getRelated(self):
        return self.relations.all()

self.relations.all()返回QuerySetPerson个对象,但我还需要从relation获取Person_Person字段

如果我获得对象本身并不重要,我只需要字段值。

1 个答案:

答案 0 :(得分:2)

您可以明确地获取这些实例,同时也可以使用select_related

class Person(models.Model):
    ...
    def get_related(self):
        qs = Person_Person.objects.select_related('cod_person_2')
        return qs.filter(cod_person_1=self)