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"
}
]
}
Try this using this custom logic.