django - 如何归还一对多

时间:2018-04-09 13:59:55

标签: django django-rest-framework

这是我的模特

class plans(models.Model):
    plan_name = models.CharField(max_length=50)
    plan_price = models.IntegerField(default=0)
    plan_is_active = models.BooleanField(max_length=1, default='1')

    def __str__(self):
        return self.plan_name

class plan_cat(models.Model):
    cat_name = models.CharField(max_length=50)
    plan = models.ForeignKey(plans, on_delete=models.CASCADE)
    cat_is_active = models.BooleanField(max_length=1, default='1')

    def __str__(self):
        return self.cat_name

我的序列化程序是

class PlanSerializer(serializers.ModelSerializer):

    class Meta:
        model = plans
        fields = ('plan_name','plan_price')


class CatSerializer(serializers.ModelSerializer):

    plan = PlanSerializer()
    class Meta:
        model = plan_cat
        fields = ('cat_name','plan')

这是我的观点

class plan_details(APIView):
    def get(self, requests):
        queryset = plan_cat.objects.filter(cat_is_active='1')
        serializer = CatSerializer(queryset, many=True)
        return Response(serializer.data)

当我调用此视图http://localhost:8000/plans/details/

获得此输出

[
    {
        "cat_name": "category 1",
        "plan": {
            "plan_name": "free",
            "plan_price": 0
        }
    },
    {
        "cat_name": "category 2",
        "plan": {
            "plan_name": "paid",
            "plan_price": 10
        }
    },
    {
        "cat_name": "category 3",
        "plan": {
            "plan_name": "free",
            "plan_price": 0
        }
    }
]

相反,我想要一个这样的输出

[
    {
        "plan_name": "free",
        "plan_price": 0,
        "cat_name": {
            "category 1",
            "category 3",
        }
    },
    {
        "plan_name": "paid",
        "plan_price": 0,
        "cat_name": {
            "category 2",
        }
    },
]

问题是外键是第二个模型, 所以我无法序列化以获得如上所述的分组内容输出。 我是否必须重写模型或序列化程序类?

1 个答案:

答案 0 :(得分:1)

您可以使用反向诉讼名称Singleton.loadSingles()。将您的视图和序列化程序重写为:

plan_cat_set

请注意,class plan_details(APIView): def get(self, requests): queryset = plans.objects.filter(cat_is_active='1') serializer = PlanSerializer(queryset, many=True) return Response(serializer.data) class CatSerializer(serializers.ModelSerializer): class Meta: model = plan_cat fields = ('cat_name',) class PlanSerializer(serializers.ModelSerializer): cat_name = CatSerializer(source='plan_cat_set', many=True) class Meta: model = plans fields = ('plan_name','plan_price', 'cat_name') 上的source='plan_cat_set'允许您将序列化程序字段名称从默认的plan_cat_set更改为CatSerializer