Django Models Relationship

19 views
Skip to first unread message

james lin

unread,
Sep 12, 2017, 2:54:55 PM9/12/17
to Django users
Hi,

I have the following models:

class UserPost(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)

class User(AbstractUser):
    MALE = 'M'
    FEMALE = 'F'
    GENDER_CHOICES = (
        (MALE, 'Male'),
        (FEMALE, 'Female')
    )
    posts = models.ManyToManyField(Post, through='UserPost')
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

class Post(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    content = models.TextField()
    status = models.CharField(max_length=100)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

When I run python manage.py makemigrations, it raises the following error:

users.User.posts: (fields.E303) Reverse query name for 'User.posts' clashes with field name 'Post.user'.
        HINT: Rename field 'Post.user', or add/change a related_name argument to the definition for field 'User.posts'.

There is a many-to-many relationship between User and Post models. Each user can like many posts and each post can be liked by many users.
There is also a many-to-one relationship between User and Post models. Each user can write many posts and each post can be written by only one user.

Shouldn't reverse query name for 'User.posts' be user_set by default. If so, why is this name clashing with field name 'Post.user'? Can someone explain the meaning of this error? Thanks.

Reply all
Reply to author
Forward
0 new messages