1👍
✅
The short answer
You should use serializers, in your case the best option is ModelSerializer.
The long answer
Firstly, you should add @property
decorator to get_age
function (I renamed it for age
):
@property
def age(self):
diff = relativedelta(datetime.date.today(),self.birthdate )
return diff
Then create serializers:
class StatusSerializer(serializers.ModelSerializer):
class Meta:
model = Status
fields = ['status_id', 'status_value']
class SomethingSerializer(serializers.ModelSerializer):
class Meta:
model = Something
fields = ['something_id', 'something_value']
class CustomerSerializer(serializers.ModelSerializer):
status = StatusSerializer()
something = SomethingSerializer(many=True)
class Meta:
model = Customer
fields = ['uuid', 'name', 'birthdate', 'status', 'something', 'age']
And then you use serializer to convert your model instance to dict:
customer_dict = CustomerSerializer(customer_model).data
Source:stackexchange.com