1

I got a model like this:

from django.db import models
from django_countries.fields import CountryField

class Location(models.Model):
    company = models.CharField(max_length=64)
    country = CountryField()

    def __unicode__(self):
        return self.company

Now I am using TastyPie for an API. I got a very simple model like this (even though I have had edited it with filters and fields before but had no success):

class LocationResource(ModelResource):
    class Meta:
        queryset = Location.objects.all()
        resource_name = 'location'

What it returns:

{"company": "testcompany", "country":"DE" "resource_uri": "/api/location/1/"}

What I would need though is the country name, or even better, anything from the Country Field.

Hi Hi
  • 366
  • 4
  • 20

3 Answers3

2

You can obtain the name from django_countries data dictionary

from django_countries.data import COUNTRIES

country_name = COUNTRIES[country_code]
Kyle_397
  • 439
  • 4
  • 14
1

you can add a dehydrate method for country to your LocationResource

def dehydrate_country(self, bundle):
    return bundle.obj.country.name 

OR

if you are using DRF instantiate Country field like

 from django_countries.serializer_fields import CountryField

 country = CountryField(country_dict=True)

in your serializer.

Satyajeet
  • 2,004
  • 15
  • 22
  • Thanks a lot :) While the `CountryField` didn't work for me (`unexpected keyword argument 'country_dict'), maybe because I misunderstood something. But using a `dehydrate` function was exactly what I needed! – Hi Hi Mar 18 '16 at 13:21
  • you are right, actually it is for DRF serializer, See the update. – Satyajeet Mar 18 '16 at 13:28
  • I am getting error: `django.db.utils.ProgrammingError: can't adapt type 'collections.OrderedDict'` when I use `country_dict = True`. So what could the possible cause? – Pran Kumar Sarkar Jan 10 '20 at 06:43
-1

In case of DRF, little bit of tweaks to the serializer could work

from django_countries.serializer_fields import CountryField
from django_countries.fields import CountryField as ModelCountryField


class CustomCountryMixin(CountryFieldMixin):
    """Custom mixin to serialize country with name instead of country code"""

    def to_representation(self, instance):
        data = super().to_representation(instance)
        for field in instance._meta.fields:
            if field.__class__ == ModelCountryField:
                if getattr(instance, field.name).name:
                    data[field.name] = getattr(instance, field.name).name
        return data



class StudentSerializer(CustomCountryMixin, serializers.ModelSerializer):

    class Meta:
        model = Student
        fields = ('mobile_number', 'study_destination', 'country_of_residence',
                  'university', 'study_level', 'course_start_date')

Surya Bhusal
  • 520
  • 2
  • 8
  • 28