在Django REST Framework中使用序列化器添加相关的ForeignKey字段

时间:2019-05-30 07:08:10

标签: django django-rest-framework django-serializer

我正在使用 Django 2.2 Django REST Framework

我有三种型号,

class Plan(models.Model):
    name = models.CharField(_('Plan Name'), max_length=100)
    default = models.NullBooleanField(default=None, unique=True)
    created = models.DateTimeField(_('created'), db_index=True)
    quotas = models.ManyToManyField('Quota', through='PlanQuota')

class Quota(models.Model):
    codename = models.CharField(max_length=50, unique=True)
    name = models.CharFieldmax_length=100)
    unit = models.CharField(max_length=100, blank=True)

class PlanQuota(models.Model):
    plan = models.ForeignKey('Plan', on_delete=models.CASCADE)
    quota = models.ForeignKey('Quota', on_delete=models.CASCADE)
    value = models.IntegerField(default=1, null=True, blank=True)

在获取计划列表时,我必须从计划序列化器中的quota中获取所有PlanQuota及其值。

我有以下序列化器

class PlanQuotaSerialier(serializers.ModelSerializer):
    class Meta:
        model = PlanQuota
        depth = 1
        fields = ['quota', 'value']


class PlanListSerializer(serializers.ModelSerializer):
    plan_quota = PlanQuotaSerialier(read_only=True, many=True)

    class Meta:
        model = Plan
        depth = 1
        fields = ['name', 'default', 'created', 'plan_quota']

但是响应中没有plan_quota

如何在单个查询(SQL JOIN)中为每个计划添加所有配额及其值?

  

编辑2:

在序列化器字段中添加source可行

plan_quota = PlanQuotaSerialier(source='planquota_set', many=True)

结果就像

"results": [
        {
            "name": "Test Plan 1",
            "default": true,
            "plan_quotas": [
                {
                    "quota": {
                        "id": 1,
                        "order": 0,
                        "codename": "TEST",
                        "name": "Test Domain",
                        "unit": "count",
                        "description": "",
                        "is_boolean": false,
                        "url": ""
                    },
                    "value": 10
                },
             ]
       }
]

我可以将quota列表中value的所有字段与plan_quotas的字段合并吗?

2 个答案:

答案 0 :(得分:0)

class PlanQuota(models.Model):
    plan = models.ForeignKey('Plan', on_delete=models.CASCADE, related_name='plan_quotas')
    quota = models.ForeignKey('Quota', on_delete=models.CASCADE)
    value = models.IntegerField(default=1, null=True, blank=True)

class PlanListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Plan
        depth = 1
        fields = ['name', 'default', 'created', 'plan_quotas']

答案 1 :(得分:0)

这就是我解决问题的方式。

  1. 对于第一个查询,添加了source

    plan_quota = PlanQuotaSerialier(source ='planquota_set',many = True)

  2. 要删除quota键,请在to_presentation()中添加PlanQuotaSerializer

    def to_representation(self, instance):
    
        representation = super().to_representation(instance)
        if 'quota' in representation:
            representation['quota']['quota_id'] = representation['quota'].pop('id')
            representation.update(representation.pop('quota'))
    
        return representation
    
相关问题