How to get top n rows in django rest framework serializers using serializers relations

995 views Asked by At

I have a serializer that is working fine for all of the data, which is getting from the Database. I want to get top n numbers of rows sorted by some value.

Below is my code in 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)

And here is my serializers.py code:

class OrgSerializers(serializers.ModelSerializer):
    team = TeamSerializer(many=True, read_only=True)
    class Meta:
        model = Organization
        fields = ['org_id','name', 'team']

And here is my TeamSerializers Code:

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

It is returning all of the team members of the same organization like below:

{
    "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

There are 3 answers

2
onkar On

Try this using this custom logic.

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)
1
KauĂȘ Oliveira On

Try this (Considering your comment as well):

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

You can patch the attribute, with:

@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)

and in the serializer, serialize top_teams instead:

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

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