Python 当每个用户添加新帖子时,如何更新我的帖子数量?
我创建了一个函数,并在用户添加帖子时在主视图中调用它。但是,当我添加新帖子时,帖子数量没有更新,并且出现以下错误:Python 当每个用户添加新帖子时,如何更新我的帖子数量?,python,django,count,Python,Django,Count,我创建了一个函数,并在用户添加帖子时在主视图中调用它。但是,当我添加新帖子时,帖子数量没有更新,并且出现以下错误: `type object 'Post' has no attribute 'post_count' 我做错了什么 这是我的模特 class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) title = models
`type object 'Post' has no attribute 'post_count'
我做错了什么
这是我的模特
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, )
title = models.CharField(max_length=100)
body = models.TextField()
date = models.DateField(auto_now_add=True)
likes = models.IntegerField(default=0)
post_count = models.PositiveIntegerField(default=0)
def __str__(self):
return self.title
这是my view.py:
def create_post(request):
context = RequestContext(request)
if request.method == 'POST':
pform = PostForm(data=request.POST, prefix='PostForm')
if pform.is_valid():
new_post = pform.save(commit=False)
new_post.user = request.user
post_count(request, new_post.user)
new_post.save()
return HttpResponseRedirect('/forum/all')
else:
pform = PostForm()
return render_to_response('forum/createpost.html',
{'pform': pform},
context)
这是我的函数,用于统计和更新每个用户的帖子数量
def post_count(request, user, **kwargs):
if user:
Post.post_count += 1
Post.save()
将post对象传递给函数,然后更改对象上的post_计数,而不是类
依赖一篇文章没有多大意义。你不是想对用户进行迁移吗?编辑模型后是否进行了迁移?你确定要使用类变量吗?@JesseBakker嗨,是的,迁移进行得很顺利。计算每个用户的登录次数效果很好,我想对帖子也这样做。@flaschbier你建议我怎么做?我会使用用户和帖子之间的关系来实现这一点。但是,如果您想使用此模型,我会在Post对象上执行此操作,而不是在类上;)是的,当用户添加帖子时,我必须更新每个用户的计数。那么我应该把post_count移到我的用户模型中吗?@Selena那么你应该改变你的用户模型。在使用身份验证模型时,应首先使用一对一关系扩展用户,以便能够添加字段。是的,好的。我会试试看它是否有效。谢谢你抽出时间。
def post_count(request, user, **kwargs):
if user:
user.post_count += 1
user.save()