如何建立与django的对称关系? [英] How do I model a symmetric relationship with django?

查看:75
本文介绍了如何建立与django的对称关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class Friendship(models.Model):
user1 = models .ForeignKey(User,related_name ='friends1')
user2 = models.ForeignKey(User,related_name ='friends2')
handshakes = models.PositiveIntegerField()
hugs = models.PositiveIntegerField )
#其他傻数据

两个朋友的友谊(user1和user2)应该是完全平等我应该可以说(user1,user2)是unique_together,而不必担心(user2,user1)意外显示。我应该能够轻松地获得给定用户的所有朋友,而是我必须编写一个自定义管理器,或者创建一些其他方式来获取该用户在该关系中的user1的所有友谊,以及所有友谊该用户是user2。



我正在考虑尝试写我自己的SymmetricKey。有人请阻止我。

解决方案

查看对称 code> ManyToManyField 在文档 - 听起来像可以做你想要的。



对于你所做的具体方式,我会做一些像

  class LameUserExtension(User):
friends = ManyToManyField(self,through = Friendship)

类友谊(models.Model):
#你在这里的东西


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.

解决方案

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

这篇关于如何建立与django的对称关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆