My get_queryset return this. Also, this fields with ID's are foreign keys serialized.
[
{
"id": 1389,
"nome": "Curso teste",
"nivel": {
"id": 5,
"nome": "Ensino Fundamental II"
},
"modalidade": {
"id": 4,
"nome": "Presencial"
},
"periodo": {
"id": 5,
"nome": "Matutino"
},
"ano": {
"id": 21,
"nome": "12º Semestre"
},
"instituicao": {
"id": 35,
"nome": "Fncit-escola"
}
}
]
I want to add to each object an extra pagination object, and it would be like this object below.
But get_queryset do not accept this kind of object, and if I use just get, and serialize the queryset, it will not come with the ForeignKeys serialized, it will return only the id's of the Foreign keys.
Anyone knows how do I return an object like this?
[
"bolsas":{
"id": 1389,
"nome": "Curso teste",
"nivel": {
"id": 5,
"nome": "Ensino Fundamental II"
},
"modalidade": {
"id": 4,
"nome": "Presencial"
},
"periodo": {
"id": 5,
"nome": "Matutino"
},
"ano": {
"id": 21,
"nome": "12º Semestre"
},
"instituicao": {
"id": 35,
"nome": "Fncit-escola"
}
},
"pagination": {
"elements": 1
}
]
I want to return this object:
retorno = {
'bolsas': bolsas,
'paginacao':{
'ultimo': True if int(totalElementos) - int(limite) == 1 else False,
'primeiro': True if pagina == 0 and int(limite) == 1 else False,
'totalPaginas': totalPaginas,
'totalElementos': totalElementos,
'elementos': elementos,
'offset': pagina
}
}
Where bolsas is the queryset
CodePudding user response:
On pure Django you have the Paginator class:
>>> from django.core.paginator import Paginator
>>> objects = ['john', 'paul', 'george', 'ringo']
>>> p = Paginator(objects, 2)
>>> p.count
4
>>> p.num_pages
2
>>> type(p.page_range)
<class 'range_iterator'>
>>> p.page_range
range(1, 3)
If you're using django-rest-framework (DRF), you have a few more options and more flexibility to customize your paginator. By limit
and offset
, with next
, cursor
pagination or some custom paginator.
Having said that, from your code examples, maybe it seems what you're looking for is a Serializer and not a Paginator? You could also leverage DRF for that or use either a simple object constructor or a Manager.
CodePudding user response:
I serialized the queryset like this:
bolsas_serialized = BolsaSerializer(bolsas, many=True).data
and then could use like this
retorno = {
'bolsas': bolsas_serialized,
'paginacao':{
'ultimo': True if int(totalElementos) - int(limite) == 1 else False,
'primeiro': True if pagina == 0 and int(limite) == 1 else False,
'totalPaginas': totalPaginas,
'totalElementos': totalElementos,
'elementos': elementos,
'offset': pagina
}
}
return Response(retorno)