我正在访问SerializerMethodField中的相关字段数据,并且每个正在呈现的对象都有一个查询。我的模型看起来像(为了简洁起见):
class Listing(models.Model):
variant = models.ForeignKey(to='Variant', related_name='variant_listings')
seller = models.ForeignKey(to='user.Seller', related_name='seller_listings')
locality = models.ForeignKey(to='user.Locality', blank=True, null=True)
price = models.IntegerField(blank=True, null=True)
Variant
,Seller
和Locality
都是相关模型。
我的观点:
class ListingViewSet(viewsets.ModelViewSet):
"""Viewset class for Listing model"""
queryset = Listing.objects.all()
serializer_class = ListingSerializer
pagination_class = TbPagination
filter_backends = (filters.DjangoFilterBackend,)
filter_class = ListingFilter
def get_queryset(self):
listing_qs = Listing.objects.filter(status='active')
listing_qs = ListingSerializer.setup_eager_loading(listing_qs)
return listing_qs
我的序列化器:
class ListingSerializer(serializers.ModelSerializer):
"""Serializer class for Listing model"""
@staticmethod
def setup_eager_loading(queryset):
queryset = queryset.prefetch_related('variant', 'seller', 'locality')
return queryset
@staticmethod
def get_car_link(obj):
variant_name_slug = obj.variant.name.replace(' ', '-').replace('+', '')
return '/buy-' + obj.seller.city.name.lower() + '/' + variant_name_slug
car_link = serializers.SerializerMethodField(read_only=True)
@staticmethod
def get_car_info(obj):
return {
'id': obj.id,
'variant_name': obj.variant.name,
'localities': obj.locality.name,
}
car_info = serializers.SerializerMethodField(read_only=True)
@staticmethod
def get_image_urls(obj):
caption_ids = [1, 2, 3, 5, 7, 8, 18]
attachments_qs = Attachment.objects.filter(listing_id=obj.id, caption_id__in=caption_ids)
image_urls = []
for attachment in attachments_qs:
url = str(obj.id) + '-' + str(attachment.file_number) + '-360.jpg'
image_urls.append(url)
return image_urls
image_urls = serializers.SerializerMethodField(read_only=True)
class Meta:
model = Listing
fields = ('car_link', 'car_info', 'sort_by', 'image_urls')
对于列表视图集返回的每个列表,都会查询SerializerMethodField中访问的每个相关字段。
我找到了一些相关问题,例如this。但这没有帮助。另外,我尝试在视图集的get_queryset方法上执行prefetch_related
,并在this文章的帮助下实现了预先加载。但没有任何帮助。
有没有办法避免这些疑问?
修改
上面写的get_car_info函数包含一些字段(以及已经存在的字段),这些字段在嵌套的JSON中需要通过前端渲染的最终序列化数据中的car_info名称单独使用。 / p>
答案 0 :(得分:0)
我用过这篇文章: http://ses4j.github.io/2015/11/23/optimizing-slow-django-rest-framework-performance/
我在序列化程序中创建了一个设置急切加载方法,如下所示:
class EagerGetProjectSerializer(serializers.ModelSerializer):
lead_researcher = UserSerializer()
participating_researcher = UserSerializer(many=True)
client = ProjectClientSerializer()
test_items = TestItemSerializer(many=True)
@staticmethod
def setup_eager_loading(queryset):
queryset = queryset.select_related('lead_researcher', 'client')
queryset = queryset.prefetch_related('participating_researcher',
'test_items')
return queryset
class Meta:
model = Project
fields = '__all__'
请注意,在引用要拉入序列化程序的对象时,必须使用与外键相关的名称属性。
并在访问序列化程序之前在我看来调用:
class SingleProject(APIView):
def get(self, request):
ans = Project.objects.filter(id=project_id)
qs = EagerGetProjectSerializer.setup_eager_loading(ans)
serializer = EagerGetProjectSerializer(qs, many=True)