sending queryset in serialzerm ethod field drf code example
Example 1: serializers.validationerror django
class HighScoreSerializer(serializers.BaseSerializer):
def to_internal_value(self, data):
score = data.get('score')
player_name = data.get('player_name')
if not score:
raise serializers.ValidationError({
'score': 'This field is required.'
})
if not player_name:
raise serializers.ValidationError({
'player_name': 'This field is required.'
})
if len(player_name) > 10:
raise serializers.ValidationError({
'player_name': 'May not be more than 10 characters.'
})
return {
'score': int(score),
'player_name': player_name
}
def to_representation(self, instance):
return {
'score': instance.score,
'player_name': instance.player_name
}
def create(self, validated_data):
return HighScore.objects.create(**validated_data)
Example 2: how to add methods to manuplate the model in serializers
from django.db import models
from django.contrib.auth.models import User
class UnivStudent(models.Model):
"""
A class based model for storing the records of a university student
Note: A OneToOne relation is established for each student with User model.
"""
user = models.OneToOneField(User)
subject_major = models.CharField(name="subject_major", max_length=60)