I'm saving an object with many to many relations in the database but when I'm fetching it so so it returns me IDs of that relational object but I want to the whole object instead, so I have added a property in the serializer and after that, it returns me the object.name only and the value of it is null, I don't know why it is behaving like this? anyone can help?
views.py
queryset = Tag.objects.filter(project_id=project_id).all()
serializer = TagSerializer(queryset, many=True)
return Response(serializer.data)
serializers.py
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
# fields = '__all__'
fields = ['id', 'name', 'description', 'singleline']
singleline = SinglelineSerializer(read_only=True)
models.py
class Tag(models.Model):
name = models.CharField(max_length=255, default='')
description = models.CharField(max_length=255, default='')
singleline = models.ManyToManyField(Singleline)
class Meta:
db_table = 'tags'
CodePudding user response:
A Tag
can have many Singleline
s, you need to work with many=True
since it is a collection:
class TagSerializer(serializers.ModelSerializer):
singleline = SinglelineSerializer(read_only=True, many=True)
class Meta:
model = Tag
fields = ['id', 'name', 'description', 'singleline']
You can improve efficiency of the view by prefetcing the singleline
relation and thus load all the related Singleline
s in bulk:
queryset = Tag.objects.filter(project_id=project_id).prefetch_related('singleline')
serializer = TagSerializer(queryset, many=True)
return Response(serializer.data)