python - 基于django的微博如何设计用户model
阿神
阿神 2017-04-17 13:32:17
[Python讨论组]

准备基于django.contrib.auth.models进行扩展,但是对于关注和粉丝这两个field的设计一直拿不准,使用foreignkey的话只能关注一人,使用manytomanyfield的话关注的这个field既可能表示关注又可能表示粉丝完全无法区分,求高手指教该如何建立这个model,谢谢。

阿神
阿神

闭关修行中......

全部回复(2)
PHP中文网

可以建一个关系表Friendship, 然后字段field分别是 粉丝和关注,并且ForeignkeyUser

class Friendship(models.Model):

    from_friend = models.ForeignKey(User, related_name = 'friend_set')
    to_friend = models.ForeignKey(User, related_name = 'to_friend_set')

可以参考这个 :社交网络中关注和粉丝的数据设计

算不上高明的方法,对于一般的需求也能解决

黄舟

采用 @rsj217 的方案就可以实现社交网络中的关注功能,除此之外也可以采用Activity Stream
来实现,Activity Stream使用了Django中的ContentType包,因此使用它可以实现任何对象之间的关注功能(例如:组的关注、资源的关注等),具体使用方式可以看一下上面的文档。

@python_2_unicode_compatible
class Follow(models.Model):
    """
    Lets a user follow the activities of any specific actor
    """
    user = models.ForeignKey(user_model_label)

    content_type = models.ForeignKey(ContentType)
    object_id = models.CharField(max_length=255)
    follow_object = generic.GenericForeignKey()
    actor_only = models.BooleanField("Only follow actions where "
                                     "the object is the target.", default=True)
    started = models.DateTimeField(default=now)
    objects = FollowManager()

    class Meta:
        unique_together = ('user', 'content_type', 'object_id')

    def __str__(self):
        return '%s -> %s' % (self.user, self.follow_object)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号