How i can to convert instance to dict with model method and relationship?
class Customer(models.Model):
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=50,,null=True,blank=True)
birthdate = models.DateField(max_length=100,null=True,blank=True)
status = models.ForeignKey('status ',on_delete=models.CASCADE)
something = models.ManyToManyField('Something',blank=True)
def get_age(self):
diff = relativedelta(datetime.date.today(),self.birthdate )
return diff
i want to convent to below
{
uuid : "value",
name : "value",
birthdate = "value",
status = {
status_id : "value"
status_text : "value"
},
something : [{
something_id : "value",
something_value : "value"
},{
something_id : "value",
something_value : "value"
}],
get_age : "value"
}
thank for every expert
CodePudding user response:
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