简体   繁体   English

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

[英]Django get object and relation field of a ManyToMany Relationship

I was wondering if this can be done with a single query 我想知道是否可以通过单个查询完成

My models.py has a model that has a M2M with itself 我的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)

Then I added this function to Person model to get all related Person 然后我将此功能添加到Person模型以获取所有相关的Person

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

self.relations.all() returns me a QuerySet with Person objects, but I also need to get the relation field from Person_Person with it self.relations.all()返回一个带有Person对象的QuerySet ,但我还需要从Person_Person获取relation字段

It doesn't really matter if I get the object itself, all I need are the field values. 获取对象本身并不重要,我只需要字段值即可。

You can get those instances explicitly, while also making use of select_related : 您可以显式获取这些实例,同时还可以使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM