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

Time:04-07

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"
        }
    ]
}

CodePudding user response:

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']

CodePudding user response:

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)
  • Related