【问题标题】:Add related ForeignKey fields with serializer in Django REST Framework在 Django REST Framework 中使用序列化程序添加相关的 ForeignKey 字段
【发布时间】:2019-05-30 07:08:10
【问题描述】:

我正在使用 Django 2.2Django REST 框架

我有三个类似的模型

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)

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

我有以下序列化程序

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 中的所有字段与plan_quotas 列表中的value 字段组合在一起吗?

【问题讨论】:

  • plan = models.ForeignKey('Plan', on_delete=models.CASCADE, related_name='plan_quota')?
  • stackoverflow.com/questions/56298645/… - 检查这个。我已经谈过了。也许这对你有帮助。
  • 我认为您的模型没有正确对齐。计划直接链接到配额以及通过 planQuota ?这两者有区别吗。如果相同,那么您可以从那里访问配额本身。

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


【解决方案1】:
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']

【讨论】:

    【解决方案2】:

    这就是我解决它的方法。

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

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

    2. 对于删除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
      

    【讨论】:

      猜你喜欢
      • 2014-08-09
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      • 2016-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-19
      相关资源
      最近更新 更多