7

I am trying to get the a CountryField (django-countries package) serialized, but my JSON does not show all the available countries.

I read here django_countries in django rest framework on what the possible solution is but I'm not getting the result.

This is what my Serializer looks like:

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')

And this is what my model looks like:

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

When I view the JSON only the saved value is shown and not all the available option to iterate over in my angularjs app.

Any direction would be appreciated.

ivanleoncz
  • 9,070
  • 7
  • 57
  • 49

1 Answers1

9

Use the CountryFieldMixin that comes with the library. There's a documented example here

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

michela
  • 498
  • 1
  • 9
  • 18