Created
July 12, 2019 23:07
-
-
Save fleepgeek/90b6d1047d6e1d672a8631102989ca1c to your computer and use it in GitHub Desktop.
Code showing how to make dynamic serializer fields in Django Rest Framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# serializers.py | |
class CategorySerializer(serializers.ModelSerializer): | |
class Meta: | |
model = Category | |
fields = ('id', 'name') | |
class TagSerializer(serializers.ModelSerializer): | |
class Meta: | |
model = Tag | |
fields = ('id', 'name') | |
class EventSerializer(serializers.ModelSerializer): | |
def __init__(self, *args, **kwargs): | |
super(EventSerializer, self).__init__(*args, **kwargs) | |
request = kwargs['context']['request'] | |
if request.method == 'GET': | |
# this returns the serializer objects for GET actions | |
# else, it returns the pk (which is what we need when we POST) | |
self.fields.update({"category": CategorySerializer()}) | |
self.fields.update({"tags": TagSerializer(many=True)}) | |
class Meta: | |
model = Event | |
fields = ( | |
'id', | |
'title', | |
'category', | |
'tags', | |
'description', | |
'event_date', | |
'location', | |
) | |
# views.py | |
class EventAPIView(generics.ListCreateAPIView): | |
serializer_class = EventSerializer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment