Django:反向访问器与反向访问器发生冲突

Django: Reverse accessor clashed with reverse accessor

在下面的代码中,我有一个 post、点赞、评论模型。当我尝试迁移模型以激活它时,出现反向访问器错误。对于点赞,user_that_liked只能点赞一次,而user_liked_to可以点赞很多次。对于评论,user_that_commented和user_commented_to都可以有很多条评论。我应该如何设置我的模型,以便我可以用模型做我想做的事,同时也解决这个问题。如果您需要更多信息,请告诉我。

from django.db import models
from django.contrib.auth.models import User


class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post_question = models.CharField(max_length=200)
    pub_date = models.DateTimeField()


class Likes(models.Model):
    user_that_liked = models.ForeignKey(User, on_delete=models.CASCADE)
    user_liked_to = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    date = models.DateTimeField()
    like_or_dislike = models.IntegerField(default=0)


class Comment(models.Model):
    user_that_commented = models.ForeignKey(User, on_delete=models.CASCADE)
    user_commented_to = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    date = models.DateTimeField()
    comment = models.CharField(max_length=300)

您需要指定相关名称以区分关系

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post_question = models.CharField(max_length=200)
    pub_date = models.DateTimeField()


class Likes(models.Model):
    user_that_liked = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_that_liked')
    user_liked_to = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_liked_to')
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    date = models.DateTimeField()
    like_or_dislike = models.IntegerField(default=0)


class Comment(models.Model):
    user_that_commented = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_that_commented')
    user_commented_to = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_commented_to')
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    date = models.DateTimeField()
    comment = models.CharField(max_length=300)

然而,携带那些用户关系感觉有点多余,因为Likes只能有user_that_liked,而user_liked_to可以从喜欢的对象派生。 (评论同上)

那么 - 可以通过 like.post.user 找到“喜欢”的用户,通过 like.user_that_liked

找到喜欢的用户