简体   繁体   中英

Add related ForeignKey fields with serializer in Django REST Framework

I'm using Django 2.2 and Django 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.

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.

How can I add all Quota and their value for each plan in a single query (SQL JOIN)?

Edit 2:

Adding source to the serializer field worked

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?

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

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

  2. For removing quota key, added to_presentation() in the 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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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