Using Django's prefetch_related on complex queries

I have the following basic query in my APIView:

categories = UserCategorizationType.objects.all() 

In the serializer, I have setup eager loading for all foreign keys and one-to-many relationships as well. However, now I need to setup eager lading for a field that is added by the serializer of UserCategorizationType. Basically, for each result in categories, I want to append a field called "possibleValues". I do this in my serializer like so:

class UserCategorizationTypeWithApprovedValuesSerialiser(BaseSerializer):    possibleValues = serializers.SerializerMethodField()     def get_possibleValues(self, categorizationType_):        #-- get all approved values and user's own values        values = UserCategorizationValue.objects.filter(             Q(categorizationType=categorizationType_) &             (                 Q(categorizations__in=UserCategorization.objects.filter(author=self.__userProfile)) | Q(state="APPROVED")             )         ).distinct()         serializer = UserCategorizationValueSerializerValueOnly(values, many=True)        return serializer.data 

My question is how do I use prefetch_related for this sort of query? I want this query to ideally stay in the serializer because there are multiple views that obtain categories and I want to encapsulate the way possibleValues are added into a category.

Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.