Last active
December 28, 2015 00:59
-
-
Save pierreant-p/7417126 to your computer and use it in GitHub Desktop.
Serializers inheritance test
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
import random | |
from django.db import models | |
from rest_framework import serializers | |
class Toto(models.Model): | |
description = models.CharField() | |
is_lol = models.BooleanField() | |
def get_a_rand(self): | |
return random.random() | |
class TotoSerializer(serializers.ModelSerializer): | |
class Meta: | |
model = Toto | |
class TotoExtendedSerializer(TotoSerializer): | |
another_field = serializers.CharField(source="get_a_rand") | |
class Meta(TotoSerializer.Meta): | |
fields = ('is_lol', 'another_field') | |
class TotoCompactSerializer(TotoSerializer): | |
class Meta(TotoSerializer.Meta): | |
fields = ('description',) | |
t = Toto() | |
t.is_lol = True | |
t.description = 'My Great Toto' | |
s = TotoSerializer(t) | |
print s.data | |
es = TotoExtendedSerializer(t) | |
print es.data | |
cs = TotoCompactSerializer(t) | |
print cs.data | |
# output | |
# >>> from skfb_toto.models import * | |
# {u'id': None, 'description': u'My Great Toto', 'is_lol': True} | |
# {'is_lol': True, 'another_field': 0.280882607255422} | |
# {'description': u'My Great Toto'} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment