gpt4 book ai didi

django-rest-framework - select_related queryset with ModelSerializer in Django rest framework

转载 作者:行者123 更新时间:2023-12-04 15:42:56 25 4
gpt4 key购买 nike

我正在尝试将“select_related”查询集方法与 DRF 序列化程序一起使用,
但是这个例子还是做了很多sql查询。

如何从 select_related 方法中获取相关对象“model_b”?

class Model_A(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
model_b = models.ForeignKey(Model_B, null=True, blank=True)

class Model_B(models.Model):
title = models.CharField(max_length=100)


class Model_A_Serializer(serializers.ModelSerializer):
model_b = Model_B_Serializer(source="model_b")
class Meta:
model = Model_A
fields = ('title', 'model_b')

class Model_B_Serializer(serializers.ModelSerializer):
class Meta:
model = Model_B


class Model_A_View(viewsets.ModelViewSet):
serializer_class = Model_A_Serializer
queryset = Model_A.objects.select_related('model_b').all()

最佳答案

Use prefetch_related instead.

queryset = Model_A.objects.all().prefetch_related('model_b')

此外,您可以使用 this answer 将 sql 查询记录到控制台。

关于django-rest-framework - select_related queryset with ModelSerializer in Django rest framework,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30986693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com