如何在 Django Rest Framework 上正确序列化来自 django_countries 的 CountryFIeld?

2024-03-09

我正在尝试序列化 CountryField (django-countries 包),但我的 JSON 并未显示所有可用的国家/地区。

我在这里读到django Rest 框架中的 django_countries https://stackoverflow.com/questions/40669313/django-countries-in-django-rest-framework可能的解决方案是什么,但我没有得到结果。

这就是我的序列化器的样子:

from django_countries.serializer_fields import CountryField

class LocationsSerializer(serializers.ModelSerializer):

country = CountryField()

class Meta:
    model = Location
    fields = ('location_name', 'address', 'city', 'province', 'postal_code', 'country')

这就是我的模型的样子:

from django_countries.fields import CountryField

class Location(models.Model):

location_name = models.CharField(max_length=100, default="None")
address = models.CharField(max_length=100)
city = models.CharField(max_length=100)
province = models.CharField(max_length=100)
postal_code = models.CharField(max_length=100)
country = CountryField()

def __str__(self):
    return self.location_name

当我查看 JSON 时,仅显示保存的值,而不是在我的 angularjs 应用程序中迭代的所有可用选项。

任何方向将不胜感激。


使用库附带的 CountryFieldMixin。这里有一个记录的示例

from django_countries.serializers import CountryFieldMixin

class CountrySerializer(CountryFieldMixin, serializers.ModelSerializer):

    class Meta:
        model = models.Person
        fields = ('name', 'email', 'country')

https://github.com/SmileyChris/django-countries https://github.com/SmileyChris/django-countries

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Django Rest Framework 上正确序列化来自 django_countries 的 CountryFIeld? 的相关文章

随机推荐