How to properly serialize a CountryFIeld from django_countries on Django Rest Framework?
Asked Answered
A

1

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.

Almire answered 1/2, 2018 at 9:35 Comment(0)
S
10

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

Stickney answered 27/8, 2020 at 11:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.