I am creating an API using Django Restframework which needs data from multiple models. I got many answers for my requirement but it isn't working.
I have my models as follows
class Task(models.Model):
title = models.CharField(max_length=200)
completed = models.BooleanField(default=False, blank=True, null=True)
def __str__(self):
return self.title
class Task_extended(models.Model):
task_id = models.ForeignKey(Task, on_delete = models.CASCADE,related_name='task_extendeds')
field_3 = models.CharField(max_length=200)
field_5 = models.CharField(max_length=200)
field_4 = models.BooleanField(default=False, blank=True, null=True)
def __str__(self):
return self.field_3
Here's my view function
@api_view(['GET','POST'])
def taskList(request):
tasks = Task.objects.all()
serializer = TaskSerializer(tasks, many =True)
return Response(serializer.data)
Serializer.py
class TaskSerializer(serializers.ModelSerializer):
task_extendeds = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = Task
fields = "__all__"
depth = 1
I am getting the json as following
[
{
"id": 2,
"task_extendeds": [
1,
2,
3
],
"title": "Start Rest Framework",
"completed": false
}
]
What changes should I do to Serializers.py so that my json output is as following
[
{
"id": 2,
"title": "Start Rest Framework",
"completed": false,
"task_extendeds": [
{
"field_3": "Field 3 Data",
"field_4": "Field 4 Data",
"field_5": "Field 5 Data"
},
{
"field_3": "Field 3 Data",
"field_4": "Field 4 Data",
"field_5": "Field 5 Data"
},
{
"field_3": "Field 3 Data",
"field_4": "Field 4 Data",
"field_5": "Field 5 Data"
}
],
}
]
The depth = 1
attribute in meta class should have got the work done according to other stackoverflow questions, but it isn't working.
CodePudding user response:
You use a subserializer, so:
class Task_extendedSerializer(serializers.ModelSerializer):
class Meta:
model = Task_extended
fields = ['field_3', 'field_4', 'field_5']
class TaskSerializer(serializers.ModelSerializer):
task_extendeds = serializers.Task_extendedSerializer(many=True)
class Meta:
model = Task
fields = '__all__'
In the view you can boost efficiency by prefetching the task_extendeds
:
@api_view(['GET'])
def taskList(request):
tasks = Task.objects.prefetch_related('task_extendeds')
serializer = TaskSerializer(tasks, many=True)
return Response(serializer.data)
Note: Models in Django are written in PascalCase, not snake_case, so you might want to rename the model from
toTask_extended
TaskExtended
.
CodePudding user response:
Write a Task_extendedSerializer
first then use it in TaskSerializer
class Task_extendedSerializer(serializers.ModelSerializer):
class Meta:
model = Task_extended
fields = ('field_3', 'field_4', 'field_5')
class TaskSerializer(serializers.ModelSerializer):
task_extendeds = Task_extendedSerializer()
class Meta:
model = Task
fields = ('id', 'title', 'completed', 'task_extendeds')