3

我无法将代码数组显示为 Django 上的嵌入字段。

  • 我将 Django 连接到有嵌入文档的 MongoDB。(见下文)MongoDB

  • 在 Django Administration 中添加字段可以正常工作。(见下文)

    Django_Admin

  • 但是,在 Django Rest Framework 上,它没有将其显示为
    嵌入式字段。

Django_Rest_Framework 前端

这是我的 Django models.py代码

from djongo import models
from django import forms


class Order(models.Model):
    code = models.CharField(max_length=3, blank=False, null=False)
    quantity = models.IntegerField()

    def __str__(self):
        return '%s %s' % (self.code, self.quantity)


class OrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = (
            'code', 'quantity'
        )


class Portfolio(models.Model):
    username = models.CharField(
        primary_key=True, max_length=65, default="", blank=False, null=False)
    codes = models.ArrayModelField(
        model_container=Order,
        model_form_class=OrderForm
    )

谢谢!

4

2 回答 2

2

After a bit of research, I found the answer on https://github.com/nesdis/djongo/issues/115.

I altered serializers.py to check for EmbeddedModelFields or ArrayModelFields:

The def get_codes checks to see if the field is an EmbeddedModelField or ArrayModelField model. If so, then accommodate the field.

from rest_framework import serializers

from portfolio.models import Portfolio

class PortfolioSerializer(serializers.ModelSerializer):
    codes = serializers.SerializerMethodField()
    class Meta:
        model = Portfolio
        fields = ('username', 'codes')

    def get_codes(self, obj):
        return_data = None
        if type(obj.codes) == list:
            embedded_list = []
            for item in obj.codes:
                embedded_dict = item.__dict__
                for key in list(embedded_dict.keys()):
                    if key.startswith('_'):
                        embedded_dict.pop(key)
                embedded_list.append(embedded_dict)
            return_data = embedded_list
        else:
            embedded_dict = obj.embedded_field
            for key in list(embedded_dict.keys()):
                if key.startswith('_'):
                    embedded_dict.pop(key)
            return_data = embedded_dict
        return return_data

Django_rest_framework

于 2019-03-23T11:07:04.020 回答
0

在 1.3.1 版中,转到 djongo 文件夹中的 fields.py 文件并复制第 465 和 466 行并在下一个 if.Done 之后添加这些行

if isinstance(value, dict):
        return value
    
if isinstance(value, ModelSubterfuge):
        value = value.subterfuge

if isinstance(value, dict):
        return value
于 2020-12-09T14:30:19.120 回答