Nuno_147
Nuno_147

Reputation: 2913

optimize SerializerMethodField in a serializer

I have a serializer like that :

class UserSerializerDetail(UserSerializer):
    active_projects = serializers.SerializerMethodField()

    def get_active_projects(self, obj):
        return obj.projects.filter(project__active=True).count()

the problem I am having here is that the SerializerMethodField is calling an extra filter and I wish to use select related to create a join and overcome another hit in the database.

The second issue is how can I select_related a count?

Upvotes: 0

Views: 135

Answers (1)

vpdiongzon
vpdiongzon

Reputation: 679

I assume the you meant user have many projects. 1 to many relationship.

The best is the combination of prefetch_related with aggregation (select_related mostly used for 1 to 1 relationship).

example:

from django.db.models import Count, Q

projects = User.objects.prefetch_related('projects').annotate(active_projects=Count('projects', filter=Q(projects__active=True)))

Then your users now have active_projects field.

Upvotes: 1

Related Questions