我有一个序列化器,它可以很好地处理从数据库获取的所有数据。我想得到按某个值排序的前n行。
下面是我在www.example.com中的代码views.py:
@api_view(['GET'])
def org_api(request, org_id):
if request.method == 'GET':
try:
org = Organization.objects.prefetch_related('team').get(org_id=org_id)
except Organization.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
serializers = OrgSerializers(org)
return Response(serializers.data)
下面是我的serializers.py代码:
class OrgSerializers(serializers.ModelSerializer):
team = TeamSerializer(many=True, read_only=True)
class Meta:
model = Organization
fields = ['org_id','name', 'team']
下面是我的TeamSerializers代码:
class TeamSerializer(serializers.ModelSerializer):
org_id = serializers.PrimaryKeyRelatedField(queryset=Team.objects.all())
class Meta:
model = Team
fields = ['name', 'resignation', 'org_id']
它返回同一组织的所有团队成员,如下所示:
{
"org_id": "ABC",
"name": "Stocks Telegraph",
"team": [
{
"name": "Mr. Timothy D. Cook",
"title": "CEO & Director",
"org_id": "ABC"
},
{
"name": "Mr. Luca Maestri",
"title": "CFO & Sr. VP",
"org_id": "ABC"
},
{
"name": "Mr. Jeffrey E. Williams",
"title": "Chief Operating Officer",
"org_id": "ABC"
},
{
"name": "Ms. Katherine L. Adams",
"title": "Sr. VP, Gen. Counsel & Sec.",
"org_id": "ABC"
},
{
"name": "Ms. Deirdre O'Brien",
"title": "Sr. VP of People & Retail",
"org_id": "ABC"
},
{
"name": "Mr. Chris Kondo",
"title": "Sr. Director of Corp. Accounting",
"org_id": "ABC"
}
]
}
3条答案
按热度按时间xtfmy6hx1#
试试这个(也考虑你的评论):
db2dz4w82#
请尝试使用此自定义逻辑。
ctzwtxfj3#
可以使用以下命令修补属性:
而在串行化器中,串行化
top_teams
: