简体   繁体   English

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

[英]Add related ForeignKey fields with serializer in Django REST Framework

I'm using Django 2.2 and Django REST Framework 我正在使用Django 2.2Django REST Framework

I have three models like 我有三个模特

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)

I have to get all quota and their value from PlanQuota in the plan serializer while getting a list of plans. 我必须在计划序列化PlanQuota中从PlanQuota获取所有quota及其价值,同时获取计划列表。

I have the following serializer 我有以下序列化程序

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']

But there is no plan_quota in the response. 但是响应中没有plan_quota

How can I add all Quota and their value for each plan in a single query (SQL JOIN)? 如何在单个查询中添加每个计划的所有配额及其值(SQL JOIN)?

Edit 2: 编辑2:

Adding source to the serializer field worked source添加到序列化器字段工作

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

And the result is like 结果就像

"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
                },
             ]
       }
]

Can I club all fields from quota with value field in the plan_quotas list? 我可以使用plan_quotas列表中的value字段来quota所有字段吗?

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']

This is how I got it solved. 这就是我解决它的方法。

  1. For the first query, added source 对于第一个查询,添加了source

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

  2. For removing quota key, added to_presentation() in the PlanQuotaSerializer 要删除quota密钥,请在PlanQuotaSerializer添加to_presentation()

     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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM