Home > Software design >  Django: Reverse accessor clashed with reverse accessor
Django: Reverse accessor clashed with reverse accessor

Time:05-09

In the code below, I have a post, likes, comment models. When I try to migrate the models to activate it, I am getting a reverse accessor error. For likes, user_that_liked only like once, while user_liked_to can have many likes. For comments, both user_that_commented and user_commented_to can have many comments. How should I set up my models so I can do what I want with the models, while also getting this issue fixed. If you need more information, let me know.

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)

CodePudding user response:

You need to specify related name to differentiate between relations

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)

However, carrying those user relations feels a bit redundant because Likes can have only user_that_liked and user_liked_to can be derived from the liked object. (Same for comment)

So then - user that "liked to" can be found via like.post.user and user that did like via like.user_that_liked

  • Related