Separate get request and database hit for each post to get like status
Question: So I am trying to make a social network on Django. Like any other social
network users get the option to like a post, and each of these likes are
stored in a model that is different from the model used for posts that show up
in the news feed. Now I have tried two choices to get the like status on the
go.

## 1.Least database hits:

Make one sql query and get the like entry for every post id if they exist.Now
I use a custom django template tag to see if the like entry for the current
post exist in the Queryset by searching an array that contains like statuses
of all posts. This way I use the database to get all values and search for a
particular value from the list using python.

## 2.Separate Database Query for each query:

Here i use the same custom template tag but rather that searching through a
Queryset I use the mysql database for most of the heavy lifting. I use
model.objects.get() for each entry.

Which is a more efficient algorithm. Also I was planning on getting another
database server, can this change the choice if network latency is only around
0.1 ms.

Is there anyway that I can get these like statuses on the go as boolean values
along with all the posts in a single db query.

## An example query for the first method can be like

Let post_list be the post QuerySet

    
    
    models.likes.objects.filter(user=current_user,post__in = post_list)
    


Answer: This is not a direct answer to your question, but I hope it is useful
nonetheless.

> and each of these likes are stored in a model that is different from the
> model used for news feed

I think you have a design issue here. It is better if you create a model that
describes a post, and then add a field `users_that_liked_it` as a [many-to-
many
relationship](https://docs.djangoproject.com/en/1.8/topics/db/examples/many_to_many/)
to your user model. Then, you can do something like `post.users_that_liked_it`
and get a query set of all users that liked your page.

In my eyes you should also avoid putting logic in templates as much as
possible. They are simply not made for it. Logic belongs into the model class,
or, if it is dependent on the page visited, in the view. (As a rule of thumb).

Lastly, if performance is your main worry, you probably shouldn't be using
Django anyway. It is just not that fast. What Django gives you is the ability
to write clean, concise code. This is much more important for a new project
than performance. Ask yourself: How many (personal) projects fail because
their performance is bad? And how many fail because the creator gets caught in
messy code?

Here is my advice: Favor clarity over performance. Especially in a young
project.

