Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I model a symmetric relationship with django?

Tags:

Let's use the classic example of friends.

class Friendship(models.Model):     user1 = models.ForeignKey(User, related_name='friends1')     user2 = models.ForeignKey(User, related_name='friends2')     handshakes = models.PositiveIntegerField()     hugs = models.PositiveIntegerField()     # other silly data 

Two friends in a friendship (user1 and user2) should be completely equal. I should be able to say that (user1, user2) are unique_together and not have to worry about (user2, user1) accidentally showing up. I should be able to get all the friends of a given user easily, but instead I'd have to write a custom manager or create some other way of getting all the Friendships where that user is user1 in the relationship, and all the Friendships where that user is user2.

I'm considering trying to write my own SymmetricKey. Someone please stop me.

like image 424
Conley Owens Avatar asked Nov 04 '10 16:11

Conley Owens


1 Answers

Check out the symmetrical option of ManyToManyField in the docs -- sounds like it can do what you want.

For the specific way you're doing it, I'd do something like

class LameUserExtension(User):     friends = ManyToManyField("self", through=Friendship)  class Friendship(models.Model):     # the stuff you had here 
like image 88
desfido Avatar answered Sep 18 '22 14:09

desfido