Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

django - Like post model with this Author already exists

What i want to do is basically user can like an article once. But this error keeps me from liking another article. Here is my code:

class LikePostModel(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.ForeignKey(User, unique=True, on_delete=models.CASCADE,related_name='postlikes',null=True)
    article = models.ForeignKey(Article,  on_delete=models.CASCADE,related_name='postlikes_set')
    created = models.DateTimeField(auto_now_add=True)

And here is my error:

Like post model with this Author already exists

How can i solve this problem?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You marked author as unique. This means that each author can only have (at most) one LikePostModel, which is probably not what you want. You probably want to make it unique per author per article. You do this with a UniqueConstraint [Django-doc]:

from django.conf import settings

class LikePostModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    # not unique=True
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='postlikes'
    )
    # not unique=True
    article = models.ForeignKey(
        Article,
        on_delete=models.CASCADE,
        related_name='postlikes_set'
    )
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        # make the combination unique
        constraints = [
            models.UniqueConstraint(fields=['author', 'article'], name='unique_like')
        ]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...