Eric Zheng
Eric Zheng

Reputation: 1144

With django, how can I retrieve if the user "likes" the article of other items?

I have 3 tables in my database, the first one is the "user" table with users' basic information, the second one is the "article" table, and the last one is the "user_like_article" table which store a record for a user and a article if the user likes the article.

For instance, if a user A like an article X, the the record in the "user_like_article" table will be like this: (A,X)

So now, I want to indicate whether the user, who has logged in, like a certain article in the article list I diplay. I have figure out a way. I first get the article list. After that, I get the list of article's id which the specific user likes. The other things work like the code below

for article in articles_to_diplay:
    if article in article_list_user_likes:
        article['like'] = True

This method works, but somehow I think it is too expensive. Displaying "like" button is just a little part of my project, but it is indeed very common. Facebook, Twitter, blogs, "like" is in widespread use.

Is there any way less expensive to accomplish this feature?

Thank you very much!

Upvotes: 0

Views: 1130

Answers (1)

mariodev
mariodev

Reputation: 15519

It's not quite simple to use some nice looking API, since we check query against logged in user object, so we need to inject is_liked method for each article object.

Also you can use ManyToManyField field for Article model, instead creating additional table (unless you're using some extra data, then let me know, so I can modify the answer accordingly.

models.py

from django.contrib.auth.models import User


class Article(models.Model):
    title = models.CharField(max_length=50)
    likes = models.ManyToManyField(User)

    def __unicode__(self):
        return self.title

views.py

def home(request):
    articles = Article.objects.all().prefetch_related('likes')
    for a in articles:
        a.is_liked = (request.user in a.likes.all())

    return render(request, 'home.html', {'articles': articles})

Upvotes: 2

Related Questions