Mojimi
Mojimi

Reputation: 3151

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

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

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

It doesn't really matter if I get the object itself, all I need are the field values.

Upvotes: 0

Views: 2501

Answers (1)

You can get those instances explicitly, while also making use of 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)

Upvotes: 2

Related Questions