Puzzled79
Puzzled79

Reputation: 1097

Django and bidirectional relationship between model

I need to store some relationship type data between a set of objects (let's call them Person's). So, some models like this:

class Person(models.Model):
    name = models.CharField(max_length=64)

class Relationship(models.Model)
    person1 = models.ForeignKey(Person, related_name='person1')
    person2 = models.ForeignKey(Person, related_name='person2')
    relationship_type = models.ChoiceField(choices=...)
    information = models.TextField()

... So, each Person can be linked to any other Person. However, some of the relationships are not directional, so it doesn't matter who is person1 or who is person2 (with this example let's say PersonA is a "friend" of PersonB). Other types of relationships are directional where the ordering does matter (say, e.g. PersonC is "the boss of" PersonD).

What's the best way to handle this in Django?

Upvotes: 2

Views: 1362

Answers (1)

unhacked
unhacked

Reputation: 131

Possible solution would be to have a two models for relationships between users. One is for directional and one for bidirectional Think about logic your program. Almost every time you fetch a user from database you need to know what kind of relationship is it. With two Relationship models you will not have such a problem. Only tradeoff of this way is that you have to make two queries to show all relations between persons - but in most cases this is not so often task.

Upvotes: 2

Related Questions