2017-10-12 49 views
0

我正在使用https://github.com/coderholic/django-cities,我想爲我的序列化程序添加城市和國家。Django <object>不是JSON可序列化

這是我的模型:

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

是否需要GeoJSON序列化程序? https://docs.djangoproject.com/en/1.11/ref/contrib/gis/serializers/這將有助於看到你如何稱它和你的requirements.txt –

+0

@DanielRoseman我訪問http://127.0.0.1 :8000/locations /這是我應該看到json的地方,一切正常,直到我添加了城市和國家的串行器 –

回答

1

您需要定義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') 
+0

我現在得到:斷言錯誤在/位置/ (「創建沒有'字段'屬性或'排除'屬性的ModelSerializer從3.3.0開始已被棄用,現在不允許添加顯式fields ='__所有__'到CountrySerializer序列化程序。「,) –

+0

@NitaAlexandru對不起,您需要在'CountrySerializer'中指定字段,或者如果您需要所有字段,請'jsut添加'fields ='__all__''。查看更新。 – neverwalkaloner

+0

啊哈,讓我看看它是否有效 –

相關問題