python - Pagination in Django Rest Framework -
i want apply pagination using django rest framework. i've following view.
def get(self,request,format=none): response_data = [] status = request.get.getlist('status') or none location = request.get.getlist('location') or none category = request.get.getlist('category') or none min_price = request.get.get('min_price') or none max_price = request.get.get('max_price') or none modela_obj = model.objects.all() if status : modela_obj = modela_obj.filter(status__in=status) if location : modela_obj = modela_obj.filter(location__in=location) if min_price : modela_obj = modela_obj.filter(minimum_expected_price__gte=int(min_price)) if max_price : modela_obj = modela_obj.filter(buyout_price__lte=int(max_price)) if category : category_list = modelb.objects.filter(subcategory__name__in=category).values_list('column',flat=true) modela_obj = modela_obj.filter(id__in=category_list) obj in modela_obj: #this fetches me details different models details = modela.get_details(obj) response_data.append(details) return response(response_data)
how paginate data? returns data. i've read api documentation, , various threads on well, hence applied following in settings.py
rest_framework = { 'default_authentication_classes': ( 'rest_framework.authentication.tokenauthentication', ), #'default_pagination_class': 'rest_framework.pagination.pagenumberpagination', #'page_size': 2, 'paginate_by': 1, 'paginate_by_param': 'page' }
but nothing seems work. url http://127.0.0.1:8000/post/?page=1
, , have 5-6 records in it, hence set page_size
1, still not working expected. how paginate data records?
edit
following models
class modela(models.model): col1 = models.charfield(max_length=255) col2 = models.textfield(blank=true,null=true) def get_details(obj): #get data modelb , modelc referenced fk `obj` class modelb(models.model): col3 = models.charfield(max_length=255) fk_a = models.foreignkey(modela) class modelc(models.model): col4 = models.charfield(max_length=255) fk_a = models.foreignkey(modela)
expected response
{ "col1": value, "col2": value, "modelb_details": [col3_value1, col3_value2....], "modelc_details": [col4_value1, col4_value2....], }, { "col1": value, "col2": value, "modelb_details": [col3_value1, col3_value2....], "modelc_details": [col4_value1, col4_value2....], }
uncomment 2 lines of code in settings
'default_pagination_class': 'rest_framework.pagination.pagenumberpagination', 'page_size': 2,
edit
in serializers
class modelaserializer(serializers.modelserializer): modelb_details=modelbserializer(source="model_b") modelc_details=modelcserializer(source="model_c") class meta: model = modela class modelbserializer(serializers.modelserializer): class meta: model = modelb fields = ('col3',) class modelcserializer(serializers.modelserializer): class meta: model = modelc fields = ('col4',)
in views
response_data = modelaserializer(objs).data
*where objs queryset of modela
Comments
Post a Comment