将数据从post传递给Serializer
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将数据从post传递给Serializer相关的知识,希望对你有一定的参考价值。
我有一些数据{iddepart,idarrivee}用于序列化程序。此数据不存在于数据模型中,但在内部用于计算某些字段:
这是我的代码,我得到错误:字段'iddepart'在序列化程序ReservationSerializer上声明,但未包含在'fields'选项中。
class TravelViewReserveSet(mixins.RetrieveModelMixin,
mixins.ListModelMixin,
mixins.DestroyModelMixin,
mixins.CreateModelMixin,
viewsets.GenericViewSet):
serializer_class = ReservationSerializer
permission_classes = (permissions.IsAuthenticated,)
Model = Travel
和序列化器:
class ReservationSerializer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
#user = UserSerializer()
#travel = TravelSerializer()
iddepart = serializers.SerializerMethodField('iddepart')
idarrivee = serializers.SerializerMethodField('idarrivee')
def create(self, validated_data):
#code= random_generator()
##code = random_generator()
reservation = Reservation(**validated_data)
reservation.code = random_generator()
reservation.save()
#iddepart = validated_data['iddepart']
#idarrivee = validated_data['idarrivee']
class Meta:
model = Reservation
fields = ('id','reservedplaces','code','datecreation','travel','user')
答案
试试这个
def create(self, validated_data):
iddepart = validated_data.pop('iddepart','default value')
idarrivee = validated_data.pop('idarrivee', 'default value')
# do somthing with this data
#code= random_generator()
##code = random_generator()
reservation = Reservation(**validated_data)
reservation.code = random_generator()
reservation.save()
#iddepart = validated_data['iddepart']
#idarrivee = validated_data['idarrivee']
另一答案
您需要将iddepart
和idarrivee
添加到Meta中的fields选项。
你的Meta应该是这样的,
class Meta:
model = Reservation
fields = ('id','reservedplaces','code','datecreation','travel','user',
'iddepart','idarrivee')
以上是关于将数据从post传递给Serializer的主要内容,如果未能解决你的问题,请参考以下文章