[英]Django model designing problem when creating a follower / following relationship
I'm trying to create a followig system for my application, and when I thought it worked, I realised that when account a started following account b, account b also started following account a我正在尝试为我的应用程序创建一个 followig 系统,当我认为它有效时,我意识到当账户 a 开始关注账户 b 时,账户 b 也开始关注账户 a
My models:我的模型:
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
followers = models.ManyToManyField('self', blank=True, related_name='followers')
following = models.ManyToManyField('self', blank=True, related_name='following')
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='p_author')
body = models.TextField(max_length=500)
time = models.TextField() #Added when creating object with the API
likes = models.IntegerField(default=0)
def serialize(self):
return {
'id': self.id,
'author': self.author.username,
'body': self.body,
'time': self.time,
'likes': self.likes
}
class Comment(models.Model):
post_commented = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='c_post')
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='c_author')
body = models.TextField(max_length=500)
time = models.TextField() #Added when creating object with the API
likes = models.IntegerField(default=0)
The view that handles the follow action (called via a JS fetch call):处理跟随操作的视图(通过 JS fetch 调用调用):
ef follow(request, profile_name):
user_object = User.objects.get(username=profile_name)
if request.method == 'PUT':
print(request.user)
data = json.loads(request.body)
if data.get('follow') == True:
followers_set = user_object.followers
followers_set.add(request.user)
user_object.save()
return JsonResponse({'status': 'success'}, status=204)
I'm supposing that I will need to restructure my whole database and project to fix this bug, how would you suggest I do it?我假设我需要重组我的整个数据库和项目来修复这个错误,你建议我怎么做?
只需添加两个用户模型假对称=属性的工作,Django的,由defauld对多对多领域的对称关系,如说在这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.