如何使用 Model 方法的源代码加快 Django Rest Framework 序列化程序的性能?



我有基于 DRF 3.6.3 的 API 端点,它已经响应(<1s 响应时间(。但是在我使用模型方法的源代码添加新的序列化程序字段后,它执行速度非常慢(响应时间超过 30 秒(。

编辑:所以性能问题,因为我在方法上处理的字段是外键。

这是我的片段代码:

class Product(models.Model):
a_name = models.CharField()
b_name = models.ForeignKey(to=OutletProduct)
def all_name(self):
return u'%s %s' % (self.a_name, self.b_name)

序列化程序:

class ProductSerializer(serializers.ModelSerializer):
productid = serializers.ReadOnlyField(source='id')
productallname = serializers.CharField(source='all_name')
class Meta:
model = Product
fields = ('productid', 'productallname')
read_only_fields = ('productallname', )

我只需要对我的 API 输出进行小的自定义,我认为覆盖to_representation()不是正确的方法。

谢谢你的帮助。

基于对 FK 的评论,我在序列化程序上覆盖了setup_eager_loading(queryset)

class ProductSerializer(serializers.ModelSerializer):
productid = serializers.ReadOnlyField(source='id')
productallname = serializers.CharField(source='all_name')
class Meta:
model = Product
fields = ('productid', 'productallname')
read_only_fields = ('productallname', )
@staticmethod
def setup_eager_loading(queryset):
# select_related for 'to-one' relationships
queryset = queryset.select_related('b_name')
return queryset

我的观点片段:

prepared_serializer = ProductSerializer.setup_eager_loading(product_list)
products = ProductSerializer(prepared_serializer, many=True)

让我知道是否有更好(更快的性能(答案。 谢谢!

最新更新