Django <object>不是JSON可序列化的

时间:2017-10-12 08:28:01

标签: python json django serialization

我正在使用https://github.com/coderholic/django-cities,我想将城市和国家/地区添加到我的序列化程序中。

这是我的模特:

from cities.models import Country, City

class Location(models.Model):
    name = models.CharField(max_length=200, blank=True, null=True, default=None)
    city = models.ForeignKey(City, blank=True, null=True, default=None, related_name='city_of_location')
    geolocation = map_fields.GeoLocationField(max_length=100, blank=True, default='')

我的观点:

class LocationsView(generics.ListAPIView):
    queryset = Location.objects.order_by('-id')
    serializer_class = LocationsSerializer

serializers.py

class LocationsSerializer(serializers.ModelSerializer):
    country = serializers.ReadOnlyField(source='city.country')

    class Meta:
        model = Location
        fields = ['id', 'name', 'geolocation', 'city', 'country']

当我试图看看它是否有效时,我正在接受:

<Country: Austria> is not JSON serializable

1 个答案:

答案 0 :(得分:2)

您需要定义CountrySerializer以序列化嵌套关系。

class CountrySerializer(serializers.ModelSerializer):
    class Meta:
        model = Country
         fields = '__all__' 

class LocationsSerializer(serializers.ModelSerializer):
    number_of_rooms = serializers.SerializerMethodField()
    country = CountrySerializer(source='city.country')

    class Meta:
        model = Location
        fields = ['id', 'name', 'geolocation', 'city', 'country']

如果您只需要国家/地区ID

,则可以使用PrimaryKeyRelatedField
country = PrimaryKeyRelatedField(source='city.country')