不能在指定中间模型的ManyToManyField上使用add()。请改用.LikeTimestamp的经理

时间:2016-04-13 11:36:54

标签: python django many-to-many

我想在我的博客中做个好像。有问题,不知道如何在这里使用经理。 猜猜这是我的主要错误。不能在指定中间模型的ManyToManyField上使用add()。请改用Posts.LikeTimestamp的经理。

我的模特:

class Like(models.Model):
    class Meta:
        db_table = 'like'
    post = models.OneToOneField(Post, null=True)
    liked_users = models.ManyToManyField(User, blank=True, through='LikeTimestamp')
    likes = models.IntegerField(default=0, blank=True)


class LikeTimestamp(models.Model):
    class Meta:
        db_table = 'liketimestamp'
    timestamp = models.DateTimeField(auto_now=True, auto_now_add=False)
    like = models.ForeignKey(Like)
    user = models.ForeignKey(User)

我的观点:

@login_required
def like_post(request, comments_id):
    try:
        like, created = Like.objects.get_or_create(comments_id=comments_id)
        like.post = Post.objects.get(id=comments_id)
        if request.user in like.liked_users.all():
            like.liked_users.remove(request.user)
            like.likes -= 1
        else:
            like.liked_users.add(request.user)
            like.likes += 1
        like.save()
    except ObjectDoesNotExist:
        raise Http404
    return redirect(request.META.get('HTTP_REFERER'))

1 个答案:

答案 0 :(得分:1)

我的朋友告诉我用户过滤器并且错误消失了。关于likes_users创建也有一个错误的界限。我应该通过时间戳模型使用创建和删除。这是正确的代码。

@login_required
def like_post(request, post_id):
    try:
        like, created = Like.objects.get_or_create(post_id=post_id)
        like.post = Post.objects.get(id=post_id)
        if like.liketimestamp_set.filter(user=request.user).exists():
            LikeTimestamp.objects.filter(like_id=like.id, user=request.user).delete()
            like.likes -= 1
        else:
            LikeTimestamp.objects.create(like_id=like.id, user=request.user)
            like.likes += 1
        like.save()
    except ObjectDoesNotExist:
        raise Http404
    return redirect(request.META.get('HTTP_REFERER'))