【问题标题】:Django Rest Framework Mongoengine - PUT/PATCH vs GET for ReferenceFieldDjango Rest Framework Mongoengine - 参考字段的 PUT/PATCH 与 GET
【发布时间】:2018-04-26 11:39:13
【问题描述】:

我有两个 mongoengine 文档 模型

from mongoengine import *

class Doc1(Document):
  doc1_field1 = StringField(max_length=100)
  doc1_field2 = StringField(max_length=100)

class Doc2(Document):
  doc2_field1 = ReferenceField(Doc1)
  doc2_field2 = StringField(max_length=100)

serializers.py中:

from rest_framework_mongoengine import serializers
from .models import Doc1, Doc2

class Doc1Serializer(serializers.DocumentSerializer):

   class Meta:          
      model = Doc1
      fields = '__all__'

class Doc2Serializer(serializers.DocumentSerializer):

   doc2_field1 = Doc1Serializer()

   class Meta:
      model = Doc2
      fields = ('doc2_field1', 'doc2_field2')

views.py

from rest_framework_mongoengine import viewsets
from .models import Doc2
from .serializers import Doc2Serializer

class Doc2ViewSet(viewsets.ModelViewSet):

   lookup_field = 'pk'

   serializer_class = Doc2Serializer

   def get_queryset(self):
     return Doc2.objects.all()

我想要实现的是,当我发出 GET 请求时,doc2_field1 应该根据 Doc1Serializer 取消引用> 这实际上是现在的情况。问题是当我尝试使用 models.py 中定义的新 ObjectID 引用来 PUT/PATCH doc2_field1 时。这就是我得到以下信息的地方:

“non_field_errors”:[ “无效数据。需要字典,但得到了字符串。” ]

所以我的问题是,是否有办法让 GET 中的字段取消引用,但允许 PUT/PATCH 中的对象引用。

预期:

获取:

{
  "doc2_field1": {
  "doc1_field1": "Text Value 1",
  "doc1_field2": "Text Value 2"
  },
  "doc2_field2": "Text Value"
}

PUT/PATCH:

{
  "doc2_field1": "5ae1a104e35e8620801798f3"
  "doc2_field2": "Text Value"
}

【问题讨论】:

  • 您能否举例说明您需要 PUT 哪些数据以及您对 GET 的期望是什么?
  • GET{ "doc2_field1": { "doc1_field1": "Text Value 1", "doc1_field2": "Text Value 2" } "doc2_field2": "Text Value" } PUT/PATCH{ "doc2_field1": "5ae1a104e35e8620801798f3" "doc2_field2": "Text Value" } PUT 一个 ReferenceId,GET 引用的对象数据

标签: python django django-rest-framework mongoengine


【解决方案1】:

您可以覆盖 Doc2Serializer 的 to_representation 方法以仅显示 GET 请求的详细信息:

class Doc2Serializer(serializers.DocumentSerializer):

   class Meta:
      model = Doc2
      fields = ('doc2_field1', 'doc2_field2')

   def to_representation(self, instance):
      self.fields['doc2_field1'] = Doc1Serializer()
      return super(Doc2Serializer, self).to_representation(instance)

【讨论】:

  • 比我想象的要简单...非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-27
  • 2023-04-05
  • 1970-01-01
  • 2014-02-03
  • 2016-10-31
  • 1970-01-01
相关资源
最近更新 更多