1

我第一次使用drf_mongoengine,並且在設置模型時遇到問題。我需要的文檔,以這樣的初始化:沒有「元數據」字段創建DocumentDocument中的EmbeddedDocument不會初始化

{ 
 
    "name" : "new_name", 
 
    "metadata": { 
 
     "total_efficiency": 0.0, 
 
     "eff_vs_layer_thickness":{ 
 
      "x":[], 
 
      "y":[] 
 
      } 
 
     } 
 
}
的文件。我錯過了什麼?

型號:

class Detector(Document): 
 
    name = fields.StringField(null=True) 
 
    metadata = fields.EmbeddedDocumentField(Metadata, null=False) 
 
    
 
class Metadata(EmbeddedDocument): 
 
    eff_vs_layer = fields.EmbeddedDocumentField(Plot) 
 
    total_efficiency = fields.DecimalField(null=True, default=0) 
 

 
class Plot(EmbeddedDocument): 
 
    x = fields.ListField(fields.FloatField(null=True), default=[]) 
 
    y = fields.ListField(fields.FloatField(null=True), default=[])

串行:

class DetectorSerializer(mongoserializers.DocumentSerializer): 
 
class Meta: 
 
    model = Detector 
 
    fields = '__all__' 
 

 
class MetadataSerializer(mongoserializers.EmbeddedDocumentSerializer): 
 
class Meta: 
 
    model = Metadata 
 
    fields = '__all__'

View: 
 
class DetectorViewSet(viewsets.ModelViewSet, mixins.UpdateModelMixin, mixins.DestroyModelMixin): 
 
    ''' 
 
    Contains information about inputs/outputs of a single program 
 
    that may be used in Universe workflows. 
 
    ''' 
 
    lookup_field = 'id' 
 
    serializer_class = DetectorSerializer

回答

0

@alvcarmona,歡迎來到DRF-ME。你通常做的都對。

只需幾件事:您不需要MetadataSerializer,因爲它將在DetectorSerializer內自動創建。

你也不要混用mixins.UpdateModelMixinmixins.DestroyModelMixin成一個完整的視圖集(viewsets.ModelViewSet),相反,它們混入rest_framework_mongoengine.generics.GenericApiView(喜歡這裏:https://github.com/umutbozkurt/django-rest-framework-mongoengine/blob/master/rest_framework_mongoengine/generics.py#L16)。

除此之外,我認爲,你做的一切都是正確的。如果你可以在github上向我展示你的項目,我可以幫助更多。

UPDATE:要混入混入普通視圖,做as we do here例如爲:

class PostPutViewSet(mixins.CreateModelMixin, 
       mixins.UpdateModelMixin, 
       GenericViewSet): 
    """ Adaptation of DRF ModelViewSet """ 
    pass 
+0

感謝@Boris Burkov,我意識到我創建沒有嵌入文檔的文件。我不明白如何將mixin混合到通用api視圖中。我的回購是這樣的:https://github.com/alvcarmona/efficiencycalculatorweb – alvcarmona

+0

@alvcarmona查看我的帖子更新的ViewSet的例子,只允許一個自定義的操作子集。 –