可能有重构目前应用的需求,rest framework是值得有必要深入去了解的。
所以,这应该是第三次看官方文档来练习,
希望能获取更深入的记忆。
__author__ = ‘CHENGANG882‘ from rest_framework import serializers from .models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES class SnippetSerializer(serializers.Serializer): pk = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, allow_blank=True, max_length=100) code = serializers.CharField(style={‘base_template‘: ‘textarea.html‘}) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default=‘python‘) style = serializers.ChoiceField(choices=STYLE_CHOICES, default=‘friendly‘) def create(self, validated_data): return Snippet.objects.create(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get(‘title‘, instance.title) instance.code = validated_data.get(‘code‘, instance.code) instance.linenos = validated_data(‘linenos‘, instance.linenos) instance.language = validated_data(‘language‘, instance.language) instance.style = validated_data(‘style‘, instance.style) instance.save() return instance
时间: 2024-11-07 13:14:11