I have two models one Country and one Office model. The office model has a ForeignKey to the Country model:
class Country(TranslatableModel):
iso = models.CharField(
max_length=2, verbose_name=_('iso code'),
help_text="ISO 3166 ALPHA-2 code")
translations = TranslatedFields(
name=models.CharField(max_length=100, verbose_name=_('name')),
)
class Office(models.Model):
country = models.ForeignKey(
Country, related_name='country', verbose_name=_('country'))
Now I want to write a django-rest-framework-serializer to send simply {"country": "us"}
to get a ForeingKey to the Country Model.
How can I achieve this?
Read-only
To simply send that representation to the client (read-only, not dealing with creating objects from their deserialized representation)
As you can see, it'll read will read
country.iso
from youroffice
instance, which resolves to'us'
e.g., then gets put into a serializer key called'country'
, given you an output of{'country': 'us'}
Writable nested field
Now to complete this, let's write a custom
OfficeSerializer.create()
:As for a
OfficeSerializer.update()
it's similar: