django实现关注与被关注

关注与被关注是现在很多网站的必需实现的功能,使用关系表也很容易表达,
下面是一一个简单的例子,

定义user表并写出设置关注与察看关注者的函数

class User(models.Model):
    username = models.CharField(max_length=30)
   
    def get_follower(self):
        '''
        folloer  关注的人
        :return:
        '''
        user_list = []
        for followed_user in self.user.followed.all():
            user_list.append(followed_user.follower)
        return user_list

    def get_followed(self):
        '''
        followed 关注我的人
        :return:
        '''
        user_list = []
        for follower_user in self.user.follower.all():
            user_list.append(follower_user.followed)
        return user_list

    def set_follower(self,id):
        '''
        follow some user use id
        :param id:
        :return:
        '''
        try:
            user = User.objects.get(id=id)
        except Exception:
            return None
        # 这是关注的逻辑
        friendship = FriendShip()
        friendship.followed = self.user
        friendship.follower = user
        friendship.save()
        return True

中间的联系两个user的关系表

class FriendShip(models.Model):
    followed = models.ForeignKey(User,related_name='followed')
    follower = models.ForeignKey(User,related_name='follower')

你可能感兴趣的:(django实现关注与被关注)