pinax-likes icon indicating copy to clipboard operation
pinax-likes copied to clipboard

How to get model likes count?

Open selcuko opened this issue 4 years ago • 2 comments

Hello devs. I am proudly using your package, but I have an issue. I'd like to get my model's total likes programmatically, will be using this to list the entries with most likes. Thank you.

selcuko avatar Aug 23 '20 18:08 selcuko

Hey. Here are some of my progress. I runned graphviz to visualize relations within models. my_project_visualized There's no obvious link between Like and Entry. When I double tabbed to see all attributes of a Like, I saw "receiver" which is a Entry. So I can see a Like's receiver, but I still cannot see an Entries likes. I am a bit confused.

selcuko avatar Aug 23 '20 18:08 selcuko

Okay. I have been inspecting your source code and came up with a solution.

@register.simple_tag
def who_likes(obj):
    """
    Usage:
        {% who_likes obj as var %}
    """
    return Like.objects.filter(
        receiver_content_type=ContentType.objects.get_for_model(obj),
        receiver_object_id=obj.pk
    )

with this code, I was able to get a model's like count within templates, now going to implement it for programmatical use. but I still cannot think of a way to effectively get the model with most likes.

selcuko avatar Aug 24 '20 10:08 selcuko