Django Rest Framework -将序列化器字段Map到数据库列名

uurity8g  于 2023-08-08  发布在  Go
关注(0)|答案(3)|浏览(143)

我正在处理Django Rest Framework项目,我的视图的通用响应不是应用程序客户端所期望的。
应用程序客户端期望相关模型的字段以它们在数据库中的原样出现。给出的示例:model City具有Country model的外键,由country_id列表示。
是否有任何选项可以将序列化器的默认字段“Map”到自定义字段?我已经检查了Django Rest Framework文档,但我只找到了“serializer_field_mapping”,但我不知道它是否符合我的要求,也不知道如何使用它。
不知何故,我得到了一个接近它的方法,但只有在获取数据的情况下-创建/更新抛出了一些错误,我不知道如何管理。:(
下面我附上我的models.py文件,加上实际输出和所需的输出。此外,如果可能的话,我想检索与国家/地区相关的数据(如果存在),并与数据库列field_id名称结合。
先谢谢你,

models.py

from django.db import models
from django.contrib.postgres.fields import ArrayField

class Country(models.Model):

    name = models.CharField(max_length=150, unique=True, blank=False)

    class Meta:
        db_table = 'countries'

class Region(models.Model):

    name = models.CharField(max_length=150, unique=True, blank=False)
    code = models.CharField(max_length=150, blank=True)

    class Meta:
        db_table = 'regions'

class City(models.Model):

    country = models.ForeignKey(Country)
    region = models.ForeignKey(Region, null=True, blank=True, default=None)
    name = models.CharField(max_length=150, unique=True, blank=False)
    postal_codes = ArrayField(models.CharField(max_length=12, blank=True), null=True, blank=True, default=None)

    def __str__(self):
        if not self.region:
            return '%s (%s)' % (self.name, self.country.name)
        return '%s, %s (%s)' % (self.name, self.region.name, self.country.name)

    class Meta:
        db_table = 'cities'

字符串

实际产量:

[
  {
    "id": 1,
    "name": "San Francisco",
    "postal_codes": null,
    "country": 1,
    "region": 1
  },
  {
    "id": 2,
    "name": "Palo Alto",
    "postal_codes": null,
    "country": 1,
    "region": 1
  },
  {
    "id": 3,
    "name": "New York City",
    "postal_codes": null,
    "country": 1,
    "region": 2
  },
  {
    "id": 4,
    "name": "London",
    "postal_codes": null,
    "country": 2,
    "region": null
  }
]

期望输出:

[
  {
    "id": 1,
    "country_id": 1,
    "region_id": 1,
    "name": "San Francisco",
    "postal_codes": null
  },
  {
    "id": 2,
    "country_id": 1,
    "region_id": 1,
    "name": "Palo Alto",
    "postal_codes": null
  },
  {
    "id": 3,
    "country_id": 1,
    "region_id": 2,
    "name": "New York City",
    "postal_codes": null
  },
  {
    "id": 4,
    "country_id": 2,
    "region_id": null,
    "name": "London",
    "postal_codes": null
  }
]

ryoqjall

ryoqjall1#

您可以在序列化程序上使用字段的source参数来实现这一点。举例来说:

from rest_framework import serializers

from .models import City

class CitySerializer(serializers.ModelSerializer):
    country_id = serializers.IntegerField(source='country')
    region_id = serializers.IntegerField(source='region')

    class Meta:
        model = City
        fields = ('id', 'country_id', 'region_id', 'name', 'postal_codes')

字符串

**编辑:**正如Yaroslav指出的,当以这种方式进行时,您不需要包含source。但是,请注意,仅仅在fields列表中包含country_idregion_id是不够的。您仍然需要在序列化器上指定字段,例如country_id = serializers.IntegerField(),并将其包含在fields中。

9o685dep

9o685dep2#

感谢所有人。我终于明白了。参见下面的代码。我回答我的问题,由于没有选择添加大量的行对一个答案的评论。

serializers.py

from rest_framework import serializers
from .models import Country, Region, City

class CountrySerializer(serializers.ModelSerializer):

    class Meta:
        model = Country
        fields = ('id', 'name')

class RegionSerializer(serializers.ModelSerializer):

    class Meta:
        model = Region
        fields = ('id', 'name', 'code')

class CitySerializer(serializers.ModelSerializer):

    country_id = serializers.PrimaryKeyRelatedField(
        queryset=Country.objects.all(),
        required=True,
        source='country',
    )
    region_id = serializers.PrimaryKeyRelatedField(
        queryset=Region.objects.all(),
        allow_null=True,
        required=False,
        source='region',
    )

    country = CountrySerializer(
        read_only=False,
        required=False,
    )
    region = RegionSerializer(
        required=False,
        allow_null=True,
        read_only=True,
    )

    class Meta:
        model = City
        fields = (
            'id',
            'country', 'region',
            'name', 'postal_codes',
            'country_id', 'region_id',
        )

字符串

rxztt3cl

rxztt3cl3#

您也可以将重命名字段设置为只读,但原始模型只写,就像。这样,在返回响应时,就不会有两个字段,一个没有id,另一个有后缀id

class CitySerializer(serializers.ModelSerializer):
    country_id = serializers.IntegerField(source='country', read_only=True)
    region_id = serializers.IntegerField(source='region', read_only=True)

    class Meta:
        model = City
        extra_kwargs = {
           "country": {"write_only": True},
           "region": {"write_only": True}
        }

字符串

相关问题