Question:
In my project, I have three models:Group
, User
and Challenge
. Each user is a member of some groups and each challenge is intended for one or more groups.Challenge
models that serializes all challenge data and related groups using a GroupSerializer
.Challenge
object, a list of all related groups is serialized.Is it possible to only serialize related
Group
objects that are also related to our currently logged in user?Answer:
you could use aSerializerMethodField()
to filter down the Challenges groups to just the user groups. To do this you may also need to pass in serializer context as wellTo set up the serializer context:
SerializerMethodField
in your serializerprefetch_related('groups')
on your queryset
in ChallengeList
to improve performanceIf you have better answer, please add a comment about this, thank you!