如何使用序列化器关系在Django REST框架序列化器中获取前N行

kiayqfof  于 2023-06-25  发布在  Go
关注(0)|答案(3)|浏览(161)

我有一个序列化器,它可以很好地处理从数据库获取的所有数据。我想得到按某个值排序的前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"
        }
    ]
}
xtfmy6hx

xtfmy6hx1#

试试这个(也考虑你的评论):

class TeamSerializer(serializers.ModelSerializer):
    ticker = serializers.PrimaryKeyRelatedField(queryset=Team.objects.all().order_by('priority')[:5])
    class Meta:
        model = Team
        fields = ['name', 'resignation', 'org_id']
db2dz4w8

db2dz4w82#

请尝试使用此自定义逻辑。

def get_limited_teams(self, request, pk=None):
    teams= Team.objects.all().order_by('priority')[:5] # Filter,order, no of rows(5) based on requirement
    serializer = TeamsSerializer(teams, many=True)
    return Reponse(serializer.data)
ctzwtxfj

ctzwtxfj3#

可以使用以下命令修补属性:

@api_view(['GET'])
def org_api(request, org_id):
    if request.method == 'GET':
        try:
            org = Organization.objects.get(org_id=org_id)
            org.top_teams = org.teams.order_by('name')[:5]  # order by some field
        except Organization.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        serializers = OrgSerializers(org)
        return Response(serializers.data)

而在串行化器中,串行化top_teams

class OrgSerializers(serializers.ModelSerializer):
    top_teams = TeamSerializer(many=True, read_only=True)

    class Meta:
        model = Organization
        fields = ['org_id', 'name', 'top_teams']

相关问题