Below is the implementation of model class 'Customer'
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 convert the django model class instance to a dictionary, somewhat like -
{
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"
}
thanks!
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