Django Rest Framework - 在不提供外键值的情况下创建

Django Rest Framework - Create without providing a foreign key value

我正在使用 Django-Rest-Framework 构建我的第一个 API,我在验证过程中遇到了一些困难。希望这是一个简单的答案,但我无法从 6 部分介绍教程中弄明白...

我有一个模型:

class XYZMeta(models.Model):
    id = models.AutoField(primary_key=True)
    xyz_id = models.ForeignKey(XYZ)
    user_id = models.ForeignKey(User)
    field_name = models.CharField(blank=True, max_length=50)
    value = models.TextField(blank=True)

还有一个序列化程序:

class XYZMetaSerializer(serializers.ModelSerializer):
    class Meta:
        model = XYZMeta
        fields = ('id', 'xyz_id', 'user_id', 'field_name', 'value')

还有一个观点:

class XYZMetaViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows xyz metadata to be viewed or edited.
    """
    queryset = XYZMeta.objects.all()
    serializer_class = serializers.XYZMetaSerializer

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

当我发送一个 POST 来创建一个新对象时,它运行良好并且使用授权用户的 ID 而不是我提供的任何值。示例:

> curl -X POST -H "Content-Type:application/json" -d '{"xyz_id":"12345",**"user_id":2**,"field_name":"abc","value":"abc comment"}' -u admin:admin http://mysite/xyzmeta/
{"id":2,"dealer_id":12345,**"user_id":1**,"field_name":"abc","value":"abc comment","create_date":"2015-02-22T23:32:27.928991Z"}

但是,如果我完全不使用 user_id(因为它并不重要),我会收到一条错误消息,指出该字段是必需的:

> curl -X POST -H "Content-Type:application/json" -d '{"xyz_id":"12345","field_name":"abc","value":"abc comment"}' -u admin:admin http://mysite/xyzmeta/
{"user_id":["This field is required."]}

如何指定我希望在创建过程中以编程方式设置 user_id 外键字段,而不必提供虚拟值?

user_id 字段只有 required=False 怎么样?

我还没有测试过这个..但是像这样的东西应该有用!

class XYZMetaSerializer(serializers.ModelSerializer):
    user_id = serializers.RelatedField(source='user_id', required=False)

    class Meta:
        [...]

一种方法:使 user_id 字段成为非必填字段

class XYZMetaSerializer(serializers.ModelSerializer):
    class Meta:
        model = XYZMeta
        fields = ('id', 'xyz_id', 'user_id', 'field_name', 'value')
        extra_kwargs = {
            'user_id': {'required': False}
        }

另一种方法:在 get_serializer(data=request.data) 方法调用之前更改 request.data

class XYZMetaViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows xyz metadata to be viewed or edited.
    """
    queryset = XYZMeta.objects.all()
    serializer_class = serializers.XYZMetaSerializer

    def create(self, request, *args, **kwargs):
        request.data['user_id'] = request.user.id
        return super(self.__class__, self).create(request, *args, **kwargs)

由于 user_id 在请求中没有用,您可以简单地从序列化程序中跳过它,然后在 ViewSet 的 perform_create 方法中添加它:

class XYZMetaViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows xyz metadata to be viewed or edited.
    """
    queryset = XYZMeta.objects.all()
    serializer_class = serializers.XYZMetaSerializer

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