B
B
blackbb2018-06-11 09:26:05
Django
blackbb, 2018-06-11 09:26:05

What is the best way to store user ids in a Django model?

Hello. On the site there is a need to fasten the rating of users who wrote the article. I did the rating, but it is necessary to implement a mechanism for checking "Like Users", i.e. Each registered user can like only once. I created a CharField field for the user and in it I store the id of the user who likes it. Rating = likes - dislikes.
User model

class Author(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    avatar = models.ImageField(upload_to='avatar', blank=True)
    like = models.IntegerField(default=0, verbose_name='Нравится')
    dislike = models.IntegerField(default=0, verbose_name='Не нравится')
    user_like_list = models.CharField(max_length=300, blank=True, verbose_name='id лайкнувших пользователей')

Like function
def add_like(request, slug):
    article = Article.objects.get(slug=slug)
    try:
        article = get_object_or_404(Article, slug=slug)
        article.author.user_like_list = article.author.user_like_list + str(request.user.id) + ','
        user_list = []
        for item in article.author.user_like_list:
            user_list.append(item)
        if request.user.id in user_list:
            return redirect('article', slug=slug)
        else:
            article.author.like += 1
            article.author.save()

How to implement it correctly and easier?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question