django rest框架嵌套关系

时间:2017-08-16 16:24:50

标签: django-rest-framework

在我的模特中

models.py

class Province(models.Model):
    name = models.CharField(max_length=128, verbose_name=u"province")

class City(models.Model):
    province = models.ForeignKey("system.Province", related_name='cities', verbose_name=u"province")
    name = models.CharField(max_length=128, verbose_name=u"name")

class District(models.Model):
    city = models.ForeignKey("system.City", related_name='districts', verbose_name=u"city")
    name = models.CharField(max_length=128, verbose_name=u"name")

serializers.py

class DistrictSerializer(serializers.ModelSerializer):
    class Meta:
        model = District
        fields = ('id', 'name')


class CitySerializer(serializers.ModelSerializer):
    districts = DistrictSerializer(many=True, read_only=True)

    class Meta:
        model = City
        fields = ('id', 'name', 'districts')


class ProvinceSerializer(serializers.ModelSerializer):
    cities = CitySerializer(many=True, read_only=True)

    class Meta:
        model = Province
        fields = ('id', 'name', 'cities')

当我向网址 / system / province / 1 / 发出 GET 请求时,我会收到json字符串

{
"id": 1,
"name": "广东省",
"cities": [
    {
        "id": 1,
        "name": "广州市",
        "districts": [
            {
                "id": 1,
                "name": "天河区"
            },
            {
                "id": 2,
                "name": "海珠区"
            }
        ]
    },
    {
        "id": 2,
        "name": "汕头市",
        "districts": [
            {
                "id": 3,
                "name": "朝阳区"
            }
        ]
    },
    {
        "id": 3,
        "name": "湛江市",
        "districts": []
    },
    {
        "id": 4,
        "name": "韶关市",
        "districts": []
    }
]

}

区域json不是我想要的。 我该如何防止自动加载区

2 个答案:

答案 0 :(得分:1)

(推荐)删除字段'区'来自meta class。

class Meta:
    model = City
    fields = ('id', 'name')

或者,如果您必须更新与此字段相关的任何值,请使用extra_kwargs变量将此字段设为write_only。

class Meta:
    model = City
    extra_kwargs = {'districts': {'write_only': True}}
    fields = ('id', 'name', 'districts')

答案 1 :(得分:0)

class DynamicFieldsModelSerializer(ModelSerializer):
    """
    A ModelSerializer that takes an additional `fields` argument that
    controls which fields should be displayed.
    """

    def __init__(self, *args, **kwargs):
        # Don't pass the 'fields' arg up to the superclass
        fields = kwargs.pop('fields', None)
        exclude = kwargs.pop('exclude', None)

        # Instantiate the superclass normally
        super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)

        if fields is not None:
            # Drop any fields that are not specified in the `fields` argument.
            allowed = set(fields)
            existing = set(self.fields.keys())
            for field_name in existing - allowed:
                self.fields.pop(field_name)

        if exclude is not None:
            not_allowed = set(exclude)
            for exclude_name in not_allowed:
                self.fields.pop(exclude_name)


class DistrictSerializer(serializers.ModelSerializer):
    class Meta:
        model = District
       fields = ('id', 'name')

class CitySerializer(DynamicFieldsModelSerializer): 
    districts = DistrictSerializer(many=True, read_only=True)

    class Meta:
        model = City
        fields = ('id', 'name', 'districts')

class ProvinceSerializer(serializers.ModelSerializer):
    cities = serializers.SerializerMethodField()

    class Meta:
        model = Province
        fields = ('id', 'name', 'cities')

    def get_cities(self, instance):
        return CitySerializer(instance.cities.all(), many=True, fields=('id', 'name')).data

int a = 1, b = 1, c = 1;

if(a == b ? a == c ? true : false : false)
{

}