I'm calling a simple get API using djangorestframework. My Model is
class Category(models.Model):
category_id = models.AutoField(primary_key=True)
category_name = models.CharField("Category Name", max_length = 30)
category_created_date = models.DateField(auto_now = True, auto_now_add=False)
category_updated_date = models.DateField(auto_now = True, auto_now_add=False)
def __str__(self):
return self.category_name
serializer.py
class CategorySerializer(serializers.ModelSerializer) :
class Meta:
model = Category
fields = ['category_id', 'category_name']
def category_list(request):
if request.method == 'GET':
categories = Category.objects.all()
serializer = CategorySerializer(categories, many=True)
return Response(serializer.data)
It's working fine when i hit request on the URL and returning following response.
[
{
"category_id": 1,
"category_name": "ABC"
}
]
i want to change the response field names as it's for my DB only and don't want to disclose in response. If i change the name in serializer class than it's giving no field match error.
Also i want to customise other params like above response in response object with message and status like below.
{
status : 200,
message : "Category List",
response : [
{
"id": 1,
"name": "ABC"
}
]
}
Need a proper guide and flow. Experts help.
You can override to_representation function in serializer.Check the following code you can update
data
dictionary as you want.First of all using
category_
in field names is redundant. Because you are already assigning this fields toCategory
model, and by doing this you are creating "namespace" for this fields.Second In django
id
AutoField is created automatically why would you need set it explicitly?And answering your question There is
source
parameter in serializer fields.And than you can change your response manually
You can just wrap it up in
json
. This is the way you render the way you want:This is the way you can rename your fields:
This is the docs for serializing with different names.
In Django 2.1.1 if you are using a viewset, you can customize the other parts of your response by overriding the
.list()
action like this