pythondjangoresttastypiedjango-countries

Django-countries and TastyPie: Get country name


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.


Solution

  • 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.