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
.
2👍
You can obtain the name from django_countries data dictionary
from django_countries.data import COUNTRIES
country_name = COUNTRIES[country_code]
- [Answered ]-Is it possible for a function to reference the class on which it's called?
- [Answered ]-Seeding a MySQL DB for a Dockerized Django App
- [Answered ]-Send weekly emails for a limited time after sign up in django
- [Answered ]-Django: what is the difference between redirect to a view function and redirect to a url (from urls.py file)
-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')
- [Answered ]-Django Static Files Not Loading in Deployment
- [Answered ]-Django Relation
- [Answered ]-Json formatting trouble, when updating or editing my json file
Source:stackexchange.com