我有两个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
应根据 {{1}取消引用} 现在实际情况就是如此。问题是当我尝试使用Doc1Serializer
中定义的新ObjectID引用PUT / PATCH doc2_field1
时。这就是我得到以下内容的地方:
“non_field_errors”:[ “数据无效。预计字典,但得到了str。” ]
所以我的问题是,是否有办法在 models.py
中取消引用字段,但允许 GET
中的对象引用。< / p>
预期:
获取:
PUT/PATCH
PUT / PATCH:
{
"doc2_field1": {
"doc1_field1": "Text Value 1",
"doc1_field2": "Text Value 2"
},
"doc2_field2": "Text Value"
}
答案 0 :(得分: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)