Created
March 21, 2016 23:17
-
-
Save jfaverie/bacd661d1c5a179e390c to your computer and use it in GitHub Desktop.
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 serializers | |
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES | |
from django.contrib.auth.models import User | |
class SnippetSerializer(serializers.ModelSerializer): | |
class Meta: | |
model = Snippet | |
fields = ('id', 'title', 'code', 'linenos', 'language', 'style', 'owner') | |
def create(self, validated_data): | |
""" | |
Create and return a new `Snippet` instance, given the validated data. | |
""" | |
return Snippet.objects.create(**validated_data) | |
def update(self, instance, validated_data): | |
""" | |
Update and return an existing `Snippet` instance, given the validated data. | |
""" | |
instance.title = validated_data.get('title', instance.title) | |
instance.code = validated_data.get('code', instance.code) | |
instance.linenos = validated_data.get('linenos', instance.linenos) | |
instance.language = validated_data.get('language', instance.language) | |
instance.style = validated_data.get('style', instance.style) | |
instance.save() | |
return instance | |
class UserSerializer(serializers.ModelSerializer): | |
snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all()) | |
class Meta: | |
model = User | |
fields = ('id', 'username', 'snippets') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment