Django:POST请求中必须填写此字段

时间:2020-10-24 16:57:21

标签: python django django-rest-framework

我正在尝试创建一个序列化程序,该序列化程序输出报告以及用户信息。 我的任务是通过以下序列化程序完成的:

class ReportSerializer(serializers.ModelSerializer):

    latitude = serializers.CharField()
    longitude = serializers.CharField()
    city = serializers.IntegerField()
    type = serializers.IntegerField()

    # We have created a field which returns a value from get_marker_icon_url
    marker_icon = serializers.SerializerMethodField('get_marker_icon_url')
    status_str = serializers.SerializerMethodField('convert_status_toStr')
    type_str = serializers.SerializerMethodField('convert_type_toStr')
    status_color = serializers.SerializerMethodField('get_status_color')
    likes = serializers.SerializerMethodField('random_likes')

    user = ReportUserSerializer()

    class Meta:
        model = Reports
        fields = [
            'user',
            'id', 
            'type',
            'city',
            'latitude', 
            'longitude',
            'likes', 
            'type_str', 
            'status_str', 
            'status_color', 
            'attached_message', 
            'marker_icon', 
            'attached_photo',
            'date_created'
        ]
...

使用此代码,我的序列化程序将返回如下响应:

[
    {
        "user": {
            "id": 1,
            "username": "3nematix",
            "profile_pic": "http://192.168.0.29:8000/frontend/static/frontend/images/reports/user_profile_pic.jpg",
            "verified": false
        },
        "id": 1,
        "type": 9,
        "city": 0,
        "latitude": "6.5123333",
        "longitude": "51.512586",
        "likes": 27,
        "type_str": "OTHER",
        "status_str": "PENDING",
        "status_color": "orange",
        "attached_message": "test",
        "marker_icon": "OTHER",
        "attached_photo": "http://192.168.0.29:8000/frontend/static/frontend/images/reports/user_profile_pic_VRjIYTs.jpg",
        "date_created": "2020-10-21T23:19:06.899302Z"
    },
    ......
]

这正是我所需要的,但是问题是,当我尝试通过POST请求创建新对象时,得到以下响应:

{
    "user": [
        "This field is required."
    ]
}

如果我要从Meta中删除'user',从user = ReportUserSerializer()类中删除ReportSerializer,那么我可以创建一个新对象,但是当我希望获得带有用户信息的报告时我需要再次添加这两个,如何解决?

1 个答案:

答案 0 :(得分:0)

您需要先填写用户字段,然后再调用保存。

这是简单的方法:

class YourView(generics.ListCreateAPIView):
    ...

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

或稍有不同:

class YourView(generics.ListCreateAPIView):
    ...
    def perform_create(self, serializer):
        serializer.validated_data['user'] = self.request.user
        return super().perform_create(serializer)