Django rest框架使用额外的字段进行了许多发布

时间:2019-06-13 18:45:58

标签: django django-models django-rest-framework

我正在尝试在Django中创建一个与具有额外字段的另一个模型具有多对多关系的模型。我正在使用rest框架在这些框架上提供CRUD操作,我相信会有一个鸡和蛋的场景...

问题是当我去发布新的MainObject时,由于没有指向MainObject的ID,它会在多对多部分中引发错误。但我希望它指向我正在创建的MainObject,在发布时尚不存在。我相信这是串行器的问题,但不确定如何解决。我假设我在制定POST数据的方式上也可能没有想到。

我正在使用Django 2.1.8

型号代码

class RelatedObject(models.Model):
    ...

class MainObject(models.Model):
    related_objects = models.ManyToManyField(RelatedObject, through='ManyRelatedObject')

class ManyRelatedObject(models.Model):
    main_object = models.ForeignKey(MainObject, on_delete=models.DO_NOTHING)
    related_object = models.ForeignKey(RelatedObject, on_delete=models.DO_NOTHING)
    other_attribute = models.BooleanField(...)

序列化器代码

class ManyRelatedObjectSerializer(serializers.ModelSerializer):
    main_object = serializers.PrimaryKeyRelatedField(queryset=MainObject.objects.all())
    related_object = serializers.PrimaryKeyRelatedField(queryset=RelatedObject.objects.all())

    class Meta:
        model = ManyRelatedObject
        fields = '__all__'


class MainObjectSerializer(serializers.ModelSerializer):
    related_object = ManyRelatedObjectSerializer(many=True)

    class Meta:
        model = MainObject
        fields = '__all__'

POST有效负载 (假设存在一个RelatedObject,其ID为1)

{
  "related_object": [
    {
      "related_object": 1,
      "other_attribute": true
    }
  ],
  ...
}

回复

{
  "related_object": [
    {
      "main_object": [
        "This field is required."
      ]
    }
  ]
}

目标响应:

{
  "id": 1,
  "related_object": [
    {
      "main_object": 1,
      "related_object": 1,
      "other_attribute": true
    }
  ],
  ...
}

REST端点设置

class MainObjectViewSet(viewsets.ModelViewSet):
    queryset = MainObject.objects.all()
    serializer_class = MainObjectSerializer

2 个答案:

答案 0 :(得分:3)

覆盖 namespace Vendor\Module\Controller\MultipleWishlist; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Customer\Model\Session; use Magento\Framework\App\Action; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Data\Form\FormKey\Validator; use Magento\MultipleWishlist\Model\WishlistEditor; use Magento\Wishlist\Controller\WishlistProviderInterface; class Add extends \Vendor\Module\Controller\Wishlist\Add { __init__() 方法。

MainObjectSerializer

此代码段的作用是,如果请求是 class MainObjectSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.context['request'].method == 'GET': self.fields['related_object'] = ManyRelatedObjectSerializer(many=True) related_object = ManyRelatedObjectSerializer(many=True)# remove this line class Meta: model = MainObject fields = '__all__',则串行器将使用 ManyRelatedObjectSerializer 串行器呈现响应/输出 ,否则将呈现 stock模式HTTP GET

答案 1 :(得分:0)

对于后代,由于时间限制,最终使用难以覆盖的createupdate方法来对此进行干扰。 django无法处理这种情况似乎很荒谬,似乎这是一个相当普遍的用例...