我的目标是构建 endpoints ,该 endpoints 将使用GenericForeignKey创建模型对象 . 由于model还包含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')
Serializer可能如下所示:
class LikeSerializer(serializers.ModelSerializer):
class Meta:
model = models.Like
fields = ('id', 'created', )
我想要实现的是根据请求中传递的键确定Like的类型 . 问题是如果在 Serializer
字段中没有明确指定DRF,则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子句 . 如您所见,根据请求中传递的键确定的类型,而不指定特殊字段 .
有没有办法实现这个目标?
谢谢
1 回答
您可以尝试在调用视图时通过将其包装在函数中来实例化您的序列化程序(您创建一个序列化工厂):
然后在视图中覆盖此方法: