Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python ';动态';DRF序列化程序中的字段_Python_Django Rest Framework - Fatal编程技术网

Python ';动态';DRF序列化程序中的字段

Python ';动态';DRF序列化程序中的字段,python,django-rest-framework,Python,Django Rest Framework,我的目标是构建端点,它将使用GenericForeignKey创建模型的对象。由于模型还包括ContentType,所以在创建对象之前,我们将引用的模型的实际类型是未知的 我将举一个例子: 我有一个“Like”模型,它可以引用一组其他模型,如“Book”、“Author” class Like(models.Model): created = models.DateTimeField() content_type = models.ForeignKey(ContentType)

我的目标是构建端点,它将使用GenericForeignKey创建模型的对象。由于模型还包括ContentType,所以在创建对象之前,我们将引用的模型的实际类型是未知的

我将举一个例子:

我有一个“Like”模型,它可以引用一组其他模型,如“Book”、“Author”

class Like(models.Model):
    created = models.DateTimeField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
序列化程序可能如下所示:

class LikeSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Like
        fields = ('id', 'created', )
我想要实现的是根据请求中传递的键来确定Like的类型。问题是,如果在
序列化程序
字段中没有明确指定,DRF不会从请求中传递这些密钥。例如,POST请求正文包含:

{
    "book":2
}
我想做下一个

def restore_object(self, attrs, instance=None)
    if attrs.get('book', None) is not None:
        # create Like instance with Book contenttype
    elif attrs.get('author', None) is not None:
        # create Like instance with Author contenttype
在这种情况下,将执行第一个if子句。 如您所见,类型是根据传入请求的键确定的,而不指定特殊字段

有没有办法做到这一点


谢谢

每当调用视图时,您可以尝试通过将其包装到函数中来实例化序列化程序(创建序列化程序工厂):

def-like_序列化器_工厂(类型_-like):
如果类型_of_like==“book”:
类LikeSerializer(serializers.ModelSerializer):
类元:
model=models.Like
字段=('id','created',)
def restore_对象(self、attrs、instance=None):
#使用Book contenttype创建类似实例
elif type_of_like==“author”:
类LikeSerializer(serializers.ModelSerializer):
类元:
model=models.Like
字段=('id','created',)
def restore_对象(self、attrs、instance=None):
#使用Author contenttype创建类似实例
回程式蒸发器
然后在视图中重写此方法:

def get_serializer_类(self):
返回类\u序列化程序\u工厂(类\u的类型)