• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Serialize filtered related fields in Django Rest framework

Resolved: Serialize filtered related fields in Django Rest framework

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

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.
I also have a serializer for Challenge models that serializes all challenge data and related groups using a GroupSerializer.
My current APIView for serializing list of challenges.
When serializing a 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 a SerializerMethodField() to filter down the Challenges groups to just the user groups. To do this you may also need to pass in serializer context as well
To set up the serializer context:
Then access this context in the SerializerMethodField in your serializer
With this implementation you could also add prefetch_related('groups') on your queryset in ChallengeList to improve performance

If you have better answer, please add a comment about this, thank you!

django django-rest-framework
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How to give rank on datetime column group by another column with userid in it

24/03/2023

Resolved: Passing 2 functions in onChange in react

24/03/2023

Resolved: Why doesn’t stringstream consume output during hex formatting?

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.