Django optimized query

Viewed 63

I have a model Personne and each person may be linked to another person via a PersonneRelation model:

class Personne(BaseModel):
    user = models.OneToOneField(User)
    relations = models.ManyToManyField('self', through='PersonneRelation',
                                       symmetrical=False,
                                       related_name='personne_relations')

class PersonneRelation(BaseModel):
    type_relation = models.IntegerField(
        choices=[(a, b) for a, b in list(PersonneEnums.TAB_RELATIONS.items())],
        default=PersonneEnums.RELATION_FRIEND)
    src = models.ForeignKey('Personne', related_name='relation_src')
    dst = models.ForeignKey('Personne', related_name='relation_dst')
    is_reverse = models.BooleanField(default=False)

So, imagine one person A. He has a contact B. My client wants me to display all the contacts of B so that A might be able to send a message to those contacts. Pretty easy. The problem is that I've made a view that displays the "person" information and it's pretty simple, like /person/{id}. Thus if you change the {id} value, you can see another person information. What I need to check is:

  • if the person to display is a contact of A
  • if the person to display is a contact... of a contact of A

For now I'm doing an ugly query where I check all the contacts... of all the contacts of A.

How would you do an optimized query to check if the person to display is a contact... of a contact of A?

1 Answers
Related