“user_id”列中的 Django REST POST 空值违反了非空约束

发送在用户字段中创建新项目的帖子请求后出现错误-它在“user_id”列中返回空值违反了非空约束详细信息:失败行包含(61,我的公司,{2,3},2020-08- 08 10:41:54.355926+00,我的描述,2、2,空)。. 我要以 JSON 格式发送的数据


{

    "name": "My Company", 

    "members":[2, 3] , 

    "user": 2, 

    "description": "My desc", 

    "status": 2, 

    "theme": 2

}

serializers.py


class AccountSerializer(serializers.ModelSerializer):

    user=serializers.StringRelatedField(read_only=False)

    class Meta:

        model=Account

        fields='__all__'


class UserSerializer(serializers.ModelSerializer):

    class Meta:

        model = User

        fields = '__all__'


class CompanySerializer(serializers.ModelSerializer):

    user = UserSerializer(read_only=True)

    def __init__(self, *args, **kwargs):

        super().__init__(*args, **kwargs)

        try:

            if self.context['request'].method in ['GET']:

                self.fields['members'] = serializers.SerializerMethodField()

        except KeyError:

            pass


    class Meta:

        model = Company

        fields = '__all__'

        

    def get_members(self, obj):

        accounts = Account.objects.filter(id__in=obj.members)

        return AccountSerializer(accounts, many=True).data

        

class CompanyListSerializer(serializers.ModelSerializer):

    class Meta: 

        model = Company

        fields = '__all__'


慕无忌1623718
浏览 114回答 1
1回答

守着一只汪

查看您的其他问题,似乎您 user = UserSerializer(read_only=True)只需要 GET 请求。如果是这样,class CompanySerializer(serializers.ModelSerializer):    def __init__(self, *args, **kwargs):        super().__init__(*args, **kwargs)        try:            if self.context['request'].method in ['GET']:                self.fields['members'] = serializers.SerializerMethodField()                self.fields['user'] = UserSerializer()        except KeyError:            pass    class Meta:        model = Company        fields = '__all__'            def get_members(self, obj):        accounts = Account.objects.filter(id__in=obj.members)        return AccountSerializer(accounts, many=True).data
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python