I am a newbie to django rest framework and have created a sample Employee
model.
My models.py:
class Employees(models.Model):
created = models.DateTimeField(auto_now_add=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
My serializers.py:
class EmployeeSerializer(serializers.Serializer):
class Meta:
model = Employees
fields = ('first_name','last_name')
This works fine but I want an additional field full_name
, which will be first_name + last_name
.
How do I define this new field full_name
in my serializers.py
?
Provided that the
Employee
is a login user, then most of us will usedjango.auth.User
, I will share howEmployee
can be implemented as anotherProfile
(extension of django User). Also with the addition offull_name.read_only
,first_name.write_only
, andlast_name.write_only
SerializerMethodField works fine, and we can also store data in serializer object and let method
get_field_name
use that.Example:
I see two ways here (I prefer the first way since you can reuse it in other parts of the app):
add a calculated property to your model and add it to your serializer by using a readonly field with source=
by using SerializerMethodField (your model unchanged)