这对我有用,djangorestframework==3.9.1:
import json
from rest_framework import serializers
from .models import WeatherLocation
class WeatherLocationSerializer(serializers.ModelSerializer):
LocationId = serializers.CharField(source='location_id')
City = serializers.CharField(source='city')
Region = serializers.CharField(source='region')
Name = serializers.CharField(source='name')
Country = serializers.CharField(source='country')
WeatherForecastLongTermTimePeriods = serializers.JSONField(required=False, allow_null=True,
source='weather_forecast_long_term_time_periods')
WeatherForecastShortTermTimePeriods = serializers.JSONField(required=False, allow_null=True,
source='weather_forecast_short_term_time_periods')
def to_representation(self, instance):
ret = super(WeatherLocationSerializer, self).to_representation(instance)
ret['WeatherForecastLongTermTimePeriods'] = json.loads(ret['WeatherForecastLongTermTimePeriods'])
ret['WeatherForecastShortTermTimePeriods'] = json.loads(ret['WeatherForecastShortTermTimePeriods'])
return ret
class Meta:
model = WeatherLocation
fields = ['LocationId', 'City', 'Region', 'Name', 'Country',
'WeatherForecastLongTermTimePeriods', 'WeatherForecastShortTermTimePeriods', ]
我认为有一种更简单的方法可以做到这一点,但是通过更改to_representation 的行为,我可以将我的文本字段转换为 JSON。供参考,这里是我的models.py:
from django.db import models
class WeatherLocation(models.Model):
"""
Weather app schema, from southparc
"""
location_id = models.CharField(primary_key=True, null=False, blank=False, default=None, max_length=254,
editable=True)
region = models.CharField(max_length=2, null=False, blank=False)
city = models.CharField(null=False, blank=False, max_length=254)
province = models.CharField(null=True, blank=True, max_length=254)
name = models.CharField(null=True, blank=True, max_length=254)
country = models.CharField(null=True, blank=True, max_length=254)
# JSON fields
weather_forecast_long_term_time_periods = models.TextField(default="", blank=True)
weather_forecast_short_term_time_periods = models.TextField(default="", blank=True)
# Dates
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
希望对您有所帮助。如果您使用 Postgres 支持的 JSONField,我相信您不需要这样做。我在这里使用 TextField 来保存我的 JSON。我认为在序列化程序上将字段类型指定为serializers.JSONField 就足够了,但事实并非如此。