all*_*llo 8 database django friend models social-network-friendship
为社交网站建立用户之间友谊的最佳方式是什么?
可能的状态是:
现在很难选择正确的模型.
很明显,A.profile.friends与其他用户有很多很多关系.
但是将朋友与朋友请求关系合并似乎是相当不洁净的.如果没有这种合并,数据就是多余的,因为"A.friends中的A而不是A.friends中的B"将是未定义的状态.
朋友查找:A.friends.filter(friends__contains = B)#rather在数据库级别进行复杂查找,对编码人员不直观
FriendRequest很明显,一个带有requester和requested_user的类,选择也很明显.
朋友模型不是很好,因为它将person1和person2作为字段,并且所有查找都需要选择具有person1 = A和person2 = B或person1 = B和person2 = A的朋友
朋友查询:Friend.objects.filter(person1 = A)union Friend.objects.filter(person2 = A)#unclean需要联合两套
另一种选择是具有朋友字段的朋友模型,这是一个很多的字段,它恰好链接到两个人.然后,选择匹配朋友字段中的一个人,然后返回模型,其中可以通过从朋友集中减去A来提取人B. 但这可能是过度的,因为没有朋友对象会有超过2个人关联.
朋友查询:Friendship.objects.filter(persons__contains = A)#queries两个表
那么,您认为存储友谊关系的最简洁,最直观的解决方案是什么?有什么常见的模式怎么做?
如果您不想重新实现所有这些友谊关系的东西,您可以使用以下模块: https: //github.com/revsys/django-friendship
它的行为是您在第三个选项中描述的:它创建单独的 ManyToMany 表。一份用于友谊请求:
class FriendshipRequest(models.Model):
""" Model to represent friendship requests """
from_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='friendship_requests_sent')
to_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='friendship_requests_received')
Run Code Online (Sandbox Code Playgroud)
另一种是友谊状态:
class Friend(models.Model):
""" Model to represent Friendships """
to_user = models.ForeignKey(AUTH_USER_MODEL, models.CASCADE, related_name='friends')
from_user = models.ForeignKey(AUTH_USER_MODEL, models.CASCADE, related_name='_unused_friend_relation')
Run Code Online (Sandbox Code Playgroud)
它还提供关注、阻止和相关管理器。