问题描述
以该序列化器的示例为例,它来自DRF文档:
Taking this example of a Serializer from the DRF docs:
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='track-detail'
)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
当DRF执行时查询以获取特定专辑
的所有曲目
,SQL生成的选择 all 每个轨道
的列。我如何将其限制为仅请求特定的列,例如 pk
用于响应中每个音轨的超链接?
When DRF does the query to fetch all the track
s for a particular album
, the SQL generated selects all of each track
's columns. How would I restrict it to only request specific columns, e.g. the pk
that would be used for the Hyperlinks to each track in the response?
(为什么?因为可能是返回的轨道的很多,每个轨道在数据库的行中都有一个 lot 的数据,这可能是返回了很多不必要的数据。)
(Why? Because there might be a lot of tracks returned and each one have a lot of data in its row in the database, which could be a lot of unnecessary data returned.)
推荐答案
我认为是这样...
from rest_framework import serializers
from rest_framework.reverse import reverse
from myapp.models import Album
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.SerializerMethodField()
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
def get_tracks(self, instance):
"Returns a list of URLs for Tracks' API detail views"
request = self.context.get('request')
tracks = []
for track in instance.tracks.values('pk'):
tracks.append(reverse(
'track-detail',
kwargs={'pk': track['pk']},
request=request
))
return tracks
我们正在手动创建 HyperlinkedRelatedField()
的结果(将URL列表返回到跟踪的API详细信息页面),但使用<$限制了从数据库中获取的数据c $ c> values()在查询集中。
We're manually creating the result of a HyperlinkedRelatedField()
(returning a list of URLs to the track's API detail pages), but restricting the data fetched from the database using values()
in the queryset.
这假定跟踪详细信息
URL模式的参数为 pk
。
This assumes that the track-detail
URL pattern has a parameter of pk
.
替换 PrimaryKeyRelatedField()
更简单。替换上面的 get_tracks()
方法:
Replacing a PrimaryKeyRelatedField()
is even simpler. Replace the get_tracks()
method above with this:
def get_tracks(self, instance):
"Returns a list of Track IDs"
return instance.tracks.values_list('pk', flat=True)
感谢@jmny让我转向使用 SerializerMethodField()
。
Thanks to @jmny for heading me towards using SerializerMethodField()
.
这篇关于在Django Rest Framework中,如何限制通过RelatedField Serializer关系获取的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!