Django: while displaying list of articles show favourite status of each articles based on the user

django multiple apps structure
django admin
django tutorial
django documentation
django create superuser
django best practices 2019
django forms
django best practices project structure

I have List of articles to be displayed as per date. Every User can mark any article as his favourite.

If a user is logged in, then he should be able to see some indication whether the article is already marked as his favourite or not.

the following are my models:

class Favourite(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    date = models.DateTimeField(auto_now_add=True)
    article = models.ForeignKey(Article, null=True,on_delete=models.CASCADE)
    class Meta:
        unique_together = ('user', 'article')

class Article(models.Model):
    title = models.CharField(max_length=256)
    intro_image = models.ImageField(null=True, blank=True, upload_to=doc_hash)
    description = models.TextField(null=True, blank=True)

I was thinking for every article get all the user ids who marked that article as favourite and then later check it at front end with the current user.

But if some article is marked as favourite by 1000 users , then unneccessarily i will have to get the data of 1000 users along with that article which is too much.

Is there a way if i pass the user i can get the favourite data only with respect to that user for each article so that i can save both on queries and amount of data to be passed to front end.

Either do that in your view's context or as a custom template tag.

The examples below are dry-coded, so they might have silly bugs.

In a view (assuming a class-based view):

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['is_favourite'] = Favourite.objects.filter(user=self.request.user, article=self.object).exists()
    return context

Usage:

{% if is_favourite %}Yay, you like it!{% endif %}

or a template tag:

@register.simple_tag(takes_context=True)
def is_favourite(context, article):
    request = context['request']
    return Favourite.objects.filter(user=request.user, article=article).exists()

Usage:

{% is_favourite article as fav %}
{% if fav %}Yay, you like it!{% endif %}
Edit

For a ListView, you can do something like

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['favourited_ids'] = set(Favourite.objects.filter(user=self.request.user, article__in=context['object_list']).values_list('article_id', flat=True))
    return context

and use it

 {% if article.id in favourited_ids %}Yay, you like this article!{% endif %}

blogs, 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​  Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

I assume that you need a flag to state if the user has already marked the article as favourite or not, suppose there are 100 articles and out of that a user has marked 40 articles as favourite then when the data would be sent then 100 articles data is sent with 40 articles having flag as read TRUE and rest as FALSE.

Following is the SQL equivalent, which you can convert to Django ORM as per your need. 'xyz' is the user id for which you need to show the articles

SELECT article.*, 
       CASE  
           WHEN read.article_id IS NOT NULL then TRUE
           ELSE FALSE
                as read_flag 
from Article as article

left join

   (select article_id from Favourite where user_id = 'xyz') as read 

   on article.id = read.article_id

Top 10 Django Mistakes, Django is a free and open source Python web framework that helpfully solves common Django my first choice because applications require a lot of work and, while I a user can configure a lot of things including the access control list (ACL​), It supports all major SQL instructions (and functions) which you can use from​  find Django based projects and packages Django people locate Djangonauts near you Django-powered sites add your site to the list Django badges show your support (or wish longingly) Django logos download official logos Django wallpaper cover your desktop Improve Django django-updates mailing list get updated for each code and ticket change (for

I found the below answer from: https://stackoverflow.com/a/51889455/2897115. Using annotations and subquery. Django can be faster using annotations and subquery which i read from. https://medium.com/@hansonkd/the-dramatic-benefits-of-django-subqueries-and-annotations-4195e0dafb16

I am putting the solution given in https://stackoverflow.com/a/51889455/2897115. Using annotations

qs = Post.objects.all()
sub = Like.objects.filter(post__id=OuterRef('pk'), user=request.user)

values = qs.annotate(
    date=Func(F('date'), function='db_specific_date_formatting_func'),
    current_user_like=Exists(sub)
).values('text, 'date', 'current_user_like')

Django Tutorial Part 6: Generic list and detail views, Here we'll learn about generic class-based views, and show how they can The book list page will display a list of all the available book records in the page, While not used here, within the loop Django will also create other In our next articles, we'll extend this library to support user accounts, and  Browse the Information Management technical library view for technical articles, demos, downloads, product documentation, and tutorials. View the list by product, title, topic, or keyword and sort your results.

What You Need to Know to Manage Users in Django Admin – Real , User management in Django admin is a tricky subject. Free Bonus: Click here to get access to a free Django Learning Resources Guide (PDF) that shows you tips <modelname> is the name of the model, in all lowercase letters. As you can see, when you're checking permissions for a superuser, the  An authoring environment for creating and/or editing user interface elements such as widgets used in a unified interest layer. The authoring environment facilitates creation of widgets that have a consistent appearance and mechanism, and allows third-party developers to easily create widgets that have a look and feel that is consistent with a predefined set of widgets.

Get Started With Django Part 1: Build a Portfolio App – Real Python, Django is a fully featured Python web framework that can be used to build complex web applications. In later posts in this series, you'll see how to build more complex websites using This is usually a database and is the base layer to an application. View displays some or all of the data to the user with HTML and CSS. Show code and output side-by-side (smaller screens will only show one at a time) Only show output (hide the code) Only show code or output (let users toggle between them) Show instructions first when loaded. pro tip You can save a copy for yourself with the Copy or Remix button. Embed Your Code! Embed this code on your site.

Building A Blog Application With Django, The homepage will list all blog posts, and there will be a dedicated detail page for we are going to use for this project if not then read the following article: Django – Web While building python projects, it's a good practice to work in virtual so that only the post with status published be shown at the front end of our blog. In this article I will explain with an example, how to display data from database in HTML Table in ASP.Net using C# and VB.Net. Database I have made use of the following table Customers with the schema as follows.

Comments
  • are you looking to filter the articles in terms of if the person has marked it as favourite or not? Suppose there are 100 articles and a user has marked favourite to 40 articles, do you want 40 articles or all the 100 articles with a flag stating the 40 which he has marked?
  • I am not showing one article per page. i am showing 50 articles in one page with pagination.
  • i have to show all the articles irrespective the user mark it as a favourite or not
  • Added an example for a ListView.
  • You mean to have two queries. One is the whole and other is the favourites. and check the whole w.r.t favourites collection.
  • The accepted answer there is equivalent to my ListView answer. The Prefetch answer there is better, even if the retrieval syntax is a little nonobvious.
  • This isn't the solution for your particular case, is it, but just a copy-paste from the other answer? It would be more beneficial to see how this approach applies to your question.
  • Sorry i forgot to put it in quotes. Since i wanted a list/queryset of posts and also to know whether or not each post is liked by a particular user. And this gives it.
  • Yes, but have you applied this solution for your models Article and Favourite? If you have, you should add that code, not the straight copy-paste.