将数据从post传递给Serializer

时间:2018-03-03 15:14:28

标签: django serialization

我在序列化程序中使用了一些数据{iddepart,idarrivee}。此数据不存在于数据模型中,但在内部用于计算某些字段:

这是我的代码,我收到错误:该字段' iddepart'已在序列化程序ReservationSerializer上声明,但尚未包含在'字段中。选项。

class TravelViewReserveSet(mixins.RetrieveModelMixin,
                 mixins.ListModelMixin,
                 mixins.DestroyModelMixin,
                 mixins.CreateModelMixin,
                 viewsets.GenericViewSet):

    serializer_class = ReservationSerializer
    permission_classes = (permissions.IsAuthenticated,)

    Model = Travel

and serialiser:

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')

2 个答案:

答案 0 :(得分:1)

试试这个

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']

答案 1 :(得分:0)

您需要在Meta中添加s = (df_2[df_2['N'] != "EX"] .sort_values(['W2','V1'],ascending=[True, False]) .drop_duplicates(['W2']) .set_index('W2')['N']) print (s) W2 b X ba ADV Name: N, dtype: object df_3 = df_2.groupby('W2', as_index=False, sort=False).sum() df_3['N'] = df_3['W2'].map(s) df_3 = df_3.reindex(columns=df_2.columns) print (df_3) W2 N V1 V2 0 ba ADV 74417 38254 1 b X 206374 56133 iddepart到字段选项。

你的Meta应该是这样的,

idarrivee