Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django_countries serializer in django rest framework

I am trying to get the django-countries 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 im not getting the result back I should, or that I think I should.

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.

like image 625
Duncan Wiggill Avatar asked Feb 01 '18 09:02

Duncan Wiggill


1 Answers

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

like image 134
michela Avatar answered Sep 30 '22 17:09

michela