How do I model a symmetric relationship with django?

后端 未结 2 2065
说谎
说谎 2020-12-25 13:14

Let\'s use the classic example of friends.

class Friendship(models.Model):
    user1 = models.ForeignKey(User, related_name=\'friends1\')
    user2 = models.         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-25 13:42

    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
    

提交回复
热议问题