对嵌套对象的HTTP请求

时间:2015-10-25 20:32:12

标签: python django post httprequest django-rest-framework

是否可以使用图书馆'请求' (用于python的HTTP库)在django rest框架中发布和更新嵌套对象?

我在序列化程序中创建了一个新的create方法,但是我无法在shell外部发布,也不能在请求库或api webview中发布。

我的序列化器:

class QualityParameterSerializer(serializers.ModelSerializer):

    class Meta:
        model = QualityParameter
        fields = ("id","name", "value")


class ProductQualityMonitorSerializer(serializers.ModelSerializer):

    parameters = QualityParameterSerializer(many=True)

    class Meta:
        model = ProductQualityMonitor
        fields = ("id","product_name", "area", "timeslot", "processing_line",
          "updated_on",'parameters')

    def create(self, validated_data):
        params_data = validated_data.pop('parameters')
        product = ProductQualityMonitor.objects.create(**validated_data)
        for param_data in params_data:
            QualityParameter.objects.create(product=product, **param_data)
        return product

POST HTTP request

1 个答案:

答案 0 :(得分:0)

如果我可以为您的序列化器建议以下表格:

from django.db import transaction

class ProductQualityMonitorSerializer(serializers.ModelSerializer):

    parameters = QualityParameterSerializer(many=True)

    class Meta:
        model = ProductQualityMonitor
        fields = (
            "id",
            "updated_on",
            "product_name", 
            "area", 
            "timeslot", 
            "processing_line", 
            "parameters", 
        )

    def create(self, validated_data):
        # we will use transactions, so that if one of the Paramater objects isn't valid
        # that we will rollback even the parent ProductQualityMonitor object creation, 
        # leaving no dangling objects in the database
        params_data = validated_data.pop('parameters')
        with transaction.atomic():
            product = ProductQualityMonitor.objects.create(**validated_data)
            # you can create the objects in a batch, hitting the dB only once
            params = [QualityParameter(product=product, **param) for param in params_data]
            QualityParameter.objects.bulk_create(params)

        return product

关于使用python请求库:发布到django后端时,你必须注意以下几个方面:

  • 您必须在请求中提供有效的CSRF令牌;这样做的方法是通过csrf-token cookie;
  • 您必须提供正确的身份验证标头/令牌/ Cookie;这是您的选择,取决于您如何在DRF后端实施此功能
  • 如果这是从一个域到另一个域的请求,那么您必须关心CORS设置。

更重要的是:你已经尝试过什么但没有用过?