Creating a follow button? How to maximize efficiency?
I'm using django. I want to create a follow button that once clicked will include the current user in the group of开发者_C百科 followers and then display the number of followers. There is a unfollow button, too, which obviously does the opposite.
My question is how I could do this with the least number of queries possible and as efficient as possible. I'm going to have a manytomany releationship between the user and the post(which is followed). So I'm guessing once I click follow/unfollow button, there's going to be one query inserting a new object into the user, user_to_post, and post tables. And retrieving the number of followers will take another query from the user_to_post table with count. I'm not sure on this, but I'm assuming this approach would take a total of 4 queries(3 inserts/deletes, 1 select).
What is a better/more efficient way of doing this?
Thanks!
IMHO:
And retrieving the number of followers will take another query from the user_to_post table with count.
You don't need to retrieve anything if you inserting something than you have it. Take this data and use them... Or even path them to your other function, like unnecessary variables or so... for e.g. you can have the number of user_to_post in your page. So it's present in your request. (if you rendering them) And you could path this variable through form and make var_count+1 or -1 depending on what you're increasing or decreasing
Why do you need to make 3 queries to post something? Show your (view or where you make query) code please... You can write it_to make a one query to write data to 3 Models... If you have fields that affect main model. For e.g. you have foreign key/many to many field with related model you can make 1 query and then access it's data through construction select_related(). See: select related Django API reference and Making queries.
Fell free to aske more specific questions with your code...
精彩评论