为什么当我在
products
中获取所有 included_lessons
而不是对象时,我只收到它们的 ID,而当我想接收完整对象时:id、名称等。
我收到的:
[
{
"id": 5,
"author": "author",
"name": "math product",
"start_time": "2024-03-01T08:25:17Z",
"min_users_in_group": 5,
"max_users_in_group": 1,
"included_lessons": [
7,
8,
9
]
}
]
我想要收到的:
[
{
"id": 5,
"author": "author",
"name": "math product",
"start_time": "2024-03-01T08:25:17Z",
"min_users_in_group": 5,
"max_users_in_group": 1,
"included_lessons": [
{
"id": 1,
"name": "some name",
"something else": "something else"
},
{
"id": 2,
"name": "some name 2",
"something else": "something else 2"
}
]
}
]
型号:
class Product(models.Model):
author = models.CharField(max_length=64)
name = models.CharField(max_length=64)
start_time = models.DateTimeField()
min_users_in_group = models.IntegerField()
max_users_in_group = models.IntegerField()
included_lessons = models.ManyToManyField(Lesson, related_name='lessons')
class Meta:
db_table = 'product'
def __str__(self):
return self.name
序列化器:
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
查看模型:
class ProductApiView(viewsets.ReadOnlyModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
我尝试在
queryset
中改变API View model
,但没用
指定子序列化器:
class LessonSerializer(serializers.ModelSerializer):
class Meta:
model = Lesson
fields = '__all__'
class ProductSerializer(serializers.ModelSerializer):
lessons = LessonSerializer(many=True)
class Meta:
model = Product
fields = '__all__'
您可以通过在一个查询中获取所有相关的
Lesson
来进一步提高性能:
class ProductApiView(viewsets.ReadOnlyModelViewSet):
queryset = Product.objects.prefetch_related('lessons')
serializer_class = ProductSerializer