Last active
July 31, 2018 08:10
-
-
Save avalanchy/941ec420cf995a8bff59dc1a1db1d366 to your computer and use it in GitHub Desktop.
django rest framework: object out - primary key in field
This file contains hidden or 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
from rest_framework import relations | |
from rest_framework.serializers import ModelSerializer | |
class ObjectOutPkInField(relations.RelatedField): | |
"""Field serializer wrapper which as normal returns related object | |
but as the input accepts object's PK (primary key). | |
Example usage: | |
>>> class TypicalModelSerializer(ModelSerializer): | |
>>> pass | |
>>> | |
>>> class ExampleUsageSerializer: | |
>>> item = ObjectOutPkInField(serializer=TypicalModelSerializer) | |
""" | |
def __init__(self, serializer, **kwargs): | |
self.serializer: ModelSerializer() = serializer | |
self.model = serializer.Meta.model | |
super().__init__(**kwargs) | |
def to_representation(self, value): | |
serializer = self.serializer(value) | |
return serializer.data | |
def to_internal_value(self, instance): | |
endpoint = self.model.objects.get(pk=instance) | |
return endpoint | |
def get_queryset(self): | |
return self.model.objects.all() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment