python - 通过序列化器创建多模型实例怎么样?

标签 python django django-rest-framework

通过序列化器创建多模型实例怎么样?

我有一个views.py:

class CloudServerCreateAPIView(CreateAPIView):
    """
    Create CloudServer
    """
    serializer_class = CloudServerCreateSerializer
    permission_classes = []
    queryset = CloudServer.objects.all()

它的序列化器是这样的:

class CloudServerCreateSerializer(ModelSerializer):

    count = serializers.IntegerField() 

    class Meta:
        model = CloudServer
        exclude = [
            'expiration_time',
            'buytime',
            'availablearea',
            'profile',
        ]

    def create(self, validated_data):

        count = validated_data.pop("count")
        for _ in range(0, count):
            # create the CloudServer instance, then save to database. And other logic stuff
        # But there must return a CloudServer instance. 

你看,我的序列化程序,我重写了 create 方法,并使用 for 循环将 CloudServer 实例保存到数据库。

但是create方法必须返回一个实例,那该怎么办呢?

因为我访问一次 View ,要创建 count 次 CloudServer 实例,在我的 create 方法中我已保存到数据库,那么我应该做什么(在这一行 # 但必须返回一个 CloudServer 实例。)?

最佳答案

如果CloudServer Model有count字段,则不能使用validated_data.pop()函数。如果有,则必须使用get()函数。

class CloudServerCreateSerializer(ModelSerializer):

    count = serializers.IntegerField() 

    class Meta:
        model = CloudServer
        exclude = [
            'expiration_time',
            'buytime',
            'availablearea',
            'profile',
        ]

    def create(self, validated_data):

        count = validated_data.pop("count")
        for _ in range(0, count):
            # create the CloudServer instance, then save to database. And other logic stuff

        return super(CloudServerCreateSerializer, self).create(validated_data)

关于python - 通过序列化器创建多模型实例怎么样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47435833/

相关文章:

python - 体素化 STL 文件?

python - 如何更新多个启用宏的 Excel 文件中的 VBA 代码?

Python 的 imp.reload() 函数不起作用?

Django Rest Framework - 注册后返回身份验证 token

Python:为什么 Tkinter 类实例化必须使用框架?

django - 小部件调整错误 ModuleNotFoundError : No module named 'widget_tweaks' with Django forms

python - Twilio 语音调用 Django/python 中的应用程序错误

django - 覆盖 Django REST Frameworks 更新方法以保存嵌套的序列化程序

apache - django Rest_framework 中缺少授权 header ,是 apache 的错吗?

python - 如何在 Django 中序列化