1

Let's say users can make a list of Types. When they add to their list of types, a new UserType object is created with the User and the Type as ForeignKeys.

Other users can 'like' the individual types that a user has listed (UserTypes).

Given that I query for a user's UserTypes, how can I best get the number of UserLikes on each UserType in a QuerySet to use in a template? Would I simply loop through, query each and return the result as a separate list? That seems pretty messy.

class Type(model.Models):
    name = models.CharField(max_length=100, blank=False)
    description = models.TextField(max_length=1000, blank=True)
    created_by = models.ForeignKey(User, blank=True, null=True, unique=False)


class UserType(model.Models):
    user = models.ForeignKey(User, unique=False)
    type = models.ForeignKey(Type, unique=False)
    is_active = models.BooleanField(default=True)


class UserLike(model.Models):
    user = models.ForeignKey(User, unique=False)
    user_type = models.ForeignKey(UserType, unique=False)

1 Answer 1

1

How about a simple count of the UserLike set for the UserType instance:

some_user_type = UserType.objects.get(user_id=some_user_pk)
like_count = some_user_type.userlike_set.all().count()

or if you have a bunch of UserTypes in a queryset you can use annotate:

from django.db.models import Count
qs = UserType.objects.annotate(Count('userlike'))

Now each result in the queryset has the count: qs[0].userlike__count

Sign up to request clarification or add additional context in comments.

3 Comments

This would return one UserType that belongs to the User and count the likes on it. I'm trying to get all UserLikes given a QuerySet of UserTypes to be used in my template.
ok, I think you should annotate the queryset...I've edited my answer
Wow, had no idea this existed. Looking at a few examples and I'm even more confused about how it works, pretty amazed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.