Django 朋友作为多对多字段 - 在字段中更好地存储 User 或 UserProfile (自身)?
我发现在 Django 中实现对称友谊系统(你是我的朋友,所以我也是你的朋友)的两种方法:
正如文档中所建议的:
class UserProfile(models.Model):
friends = models.ManyToManyField(User, related_name='friends')
现在,我想让所有“友好” “用户和用户配置文件模型具有一个 select_lated-query,如下所示(这应该是反向连接查找):
profiles = UserProfile.objects.filter(user__in=request.user.get_profile().friends.all()).select_related()
我查询用户配置文件,因为这样,我可以使用 select_lated() 并且所有相关对象都会被缓存。
另一方面,我可以定义我的模型,将朋友字段引用为“self”,如下所示:
class UserProfile(models.Model):
friends = models.ManyToManyField('self')
现在,我的 select_lated 朋友查找看起来像这样:
profiles = this_user.get_profile().friends.all().select_related()
我总是需要用户对象及其相关个人资料: 第二种方法是很多通过 select_lated() 进行反向查找更简单,但实际上是相同的。然而,通过使用“self”作为字段引用,Django 为我处理了对称的友谊。因此,我不必在数据库中为每个友谊手动创建两个条目。姜戈为我做到了这一点。然而,对称选项仅适用于“自我”引用字段。
哪个是更好的解决方案?我找不到任何相关信息。任何想法表示赞赏 - 谢谢!
I found two ways of implementing a symmetrical friendship system (you are my friend, so I am also your friend) in Django:
As suggested inside the docs:
class UserProfile(models.Model):
friends = models.ManyToManyField(User, related_name='friends')
Now, I'd like to get all "friendly" user AND userprofile models with one select_related-query like so (that should be a reverse joined lookup):
profiles = UserProfile.objects.filter(user__in=request.user.get_profile().friends.all()).select_related()
I query the userprofile, because that way, I can use select_related() and all related objects are cached.
On the other hand, I can define my model referencing the friends field to "self", like so:
class UserProfile(models.Model):
friends = models.ManyToManyField('self')
Now, my select_related friend lookup looks like that:
profiles = this_user.get_profile().friends.all().select_related()
I always need both, the user object and it's related profile: The second approach is much simpler concerning the reversed lookup via select_related(), but does practically the same. However, by using "self" as field reference, Django handles for me the symmetrical friendship. Thus, I don't have to create two entries per friendship in the database manually. Django does that for me. The symmetrical option, however, does only work on "self" referencing fields.
Which is the better solution? I can't find anything about it. Any ideas appreciated - thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Simon,
有时最好使用现有的插件,而不是尝试重新发明轮子。
您看过 django-friends 吗?
Simon,
Sometimes its better to use an existing plugin, rather than trying to re-invent the wheel.
Have you had a look at django-friends?