This is my requirement to obtain the total number of "likes" for a specified user.
User models. py
class UserProfile(models.Model): user = models.OneToOneField(User)
Topic \ reply models. py
class Reply(models.Model): content = models.TextField() author = models.ForeignKey(User) ... thanks = models.ManyToManyField(User,related_name=‘+‘)
Each reply is a reply. Every time you get a consent, thanks has a more corresponding relationship.
I want to filter out all his replies by specifying a user and then obtain the total number of his/her replies.
In the views view, I can use the following code to obtain the total number of "likes" for a person.
thanks_count = 0for reply in Reply.objects.filter(author=user_profile.user): thanks_count += reply.thanks.count()
ThenReply_thanks.htmlIn the template, I can use thanks_count to get the total number of likes.
------
The above method did not take long to find its drawbacks. Because the number of likes to be displayed next to the profile picture of each user on the pasting sub-interface, "author = user_profile.user" cannot be used for multiple users.
Therefore, a new, simple, and highly available method is required. I have thought about adding the like attribute to USERPROFILE, or loop through the layer in the retrieved reply and then get the user. However, they are all in trouble and are not powerful. They don't know how to implement it.
So I began to look at the code in the template to see if I could find something. I saw "{item. Author. get_profile.slug}" in index.html. The topic can get the user. Can I get the number of thanks from the user?
The answer is yes.
Reply and userprefile are established through the user. Use in the template{Item. Author. USERPROFILE. get_user_thanks }}You can get the method in userprefile. It is worth noting that the userprefile is in lower case. If the user is obtained, the user prefile can be obtained directly.
It is indeed a result.
Next DefinitionGet_user_thanksThat's simple. Add a function to USERPROFILE.
class UserProfile(models.Model): user = models.OneToOneField(User) def get_user_thanks(self): thanks_count = 0 for reply in Reply.objects.filter(author=self.user): thanks_count += reply.thanks.count() return thanks_count
In this way, in the template, you can easily use this method to retrieve user likes, whether it is a topic or a reply.
Trivial records queried by Django