Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve the problem of shrinking in static file?
I loaded the static in Django and it loaded. All the files loaded. There is no problem showing in the console but the template is shrunk. All the details and images are looking so small. How to deal with that? Any file which you will require, I will update it. But please let me know. -
How to deploy django with nginx and uwsgi
i have a problem to deploy my django server with uwsgi and nginx. The command dev_ralph runserver 0.0.0.0:8000 starts the development server and works fine. But my goal now is to deploy a production django server and as i said, i have some problems with that. My project-root-directory is: /home/ralphadmin/uwsgi/capentory-ralph/ralph Here is the nginx-virtualhost-configuration: /etc/nginx/sites-available/ralph.conf and /etc/nginx/sites-enabled/ralph.conf: # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { # server unix:///home/ralphadmin/uwgsi/capentory-ralph/ralph/mysite.sock; # for a file socket server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 80; # the domain name it will serve for server_name 10.70.7.1; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /var/media; # your Django project's media files - amend as required } location /static { root /home/ralphadmin/uwsgi/capentory-ralph/ralph/src/ralph/static/; # your Django project's static files } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/ralphadmin/uwsgi/capentory-ralph/ralph/uwsgi_params; # the uwsgi_params file you ins$ } } As you can see, … -
Django query of a few data (1k-3k) is taking too long (minutes)
Okay I have a django app with the following conditions: Hosted @: PythonAnywhere Database: SQLite and MySQL PROBLEM: At first with few hundreds of data its work okay, but when I reach a few thousands (3k) it takes too long to load it on a simple table. MY CODE: models.py class Outgoing(models.Model): base_in = models.ForeignKey('warehouse.Incoming', related_name='out', on_delete = models.SET_NULL, null=True) trans_date = models.DateField('Date', default=timezone.now) trans_type = models.CharField('Type', max_length=50, choices = OUTGOING_TYPE) form_no = models.CharField('FORM No', max_length=20, default=0) project_site = models.ForeignKey(ProjectSite, related_name='out_project_site', null=True, on_delete = models.SET_NULL) released_by = models.ForeignKey(User, related_name='out_released_by', default='', on_delete = models.SET_NULL, null=True) released_to = models.ForeignKey(User, related_name='out_released_to', blank=True, null=True, on_delete = models.SET_NULL) released_out = models.ForeignKey(Outsider, related_name='outsider_released_to', blank=True, null=True, on_delete = models.SET_NULL) unit = models.ForeignKey(UnitProfile, related_name='user_unit', blank=True, null=True, on_delete = models.SET_NULL) quantity = models.DecimalField('Quantity', db_index=True, max_digits=20, decimal_places=2, default=0) details = models.CharField('Details', max_length=200, default='') attachment = models.FileField('Form', upload_to='incoming_form', blank=True) create_date = models.DateTimeField('Date Created', auto_now_add=True) def __str__(self): return "%s" %(self.trans_date) class Meta: verbose_name = 'Outgoing' verbose_name_plural = 'Outgoings' views.py class OutgoingView(ListView): model = Outgoing template_name = 'warehouse/outgoing_page.html' context_object_name = 'all_out' outgoing_page.html <tbody> {% for outgoing in all_out%} <tr> <td class="text-truncate">{{ outgoing.trans_date }}</td> <td class="text-truncate">{{ outgoing.trans_type }}</td> <td class="text-truncate">{{ outgoing.form_no }}</td> <td class="text-truncate info">{{ outgoing.base_in.item }}</td> <td class="text-truncate danger">{{ outgoing.quantity|intcomma }}</td> <td class="text-truncate">{{ … -
Serving media files and static files from Amazon S3 to Django/Heroku
I've got a question about serving media files and static files from an S3 bucket. I'd be extremely grateful if anyone could give some pointers about how to solve the problem. Background I've completed a number of tutorials to get a basic idea for how Django works. To cement what I've learnt, I've decided to repurpose a lot of the concepts into a simple web app and deploy it online. https://tbdcl-allconf-production.herokuapp.com/ https://www.allconf.io/ The site shows a list of conferences, which have a one-to-many relationship with a conference series (e.g. DjangoCon parent with DjangoCon 2019 and DjangoCon 2020 as children). The conference series has a logo image as part of its model. The image is displayed as part of a card in a list of all conferences: https://tbdcl-allconf-production.herokuapp.com/conferences/ https://www.allconf.io/conferences/ These are all added through the admin, as it's not intended for users to be able to update the conference list. Problem Everything worked fine when working locally, BUT when I deployed to Heroku the logos would not display (even though the files were visible in the admin view in the deployed app). A quick search revealed that Heroku cannot serve media files, so I chose the (seemingly) most common approach – … -
Suggestion needed: How to visit everys single reply in django
I am developing a comment part of the blog API. I have the model as followings. class Comment(models.Model): author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) comment = models.TextField() created_at = models.DateTimeField(auto_now_add=True) parent = models.ForeignKey( 'self', related_name='reply', null=True, blank=True, on_delete=models.CASCADE) objects = CommentManager() def __str__(self): if self.parent is None: return "{}'s comment".format(str(self.author)) return "{}'s reply".format(str(self.author)) My Problem: I am strugling to get the all replies. I am getting only first depth commnts. # gets parent comments well. comment = Comment.objects.filter(parent__isnull=True) # If I want to get child comment # gets only the first depth comments comment.reply.all() I need a suggestion: Please give any idea to retrieve all reply comments. -
Django context does not render in base template
I appreciate that similar questions have been asked before, but after looking at them, I still cannot seem to solve my issue. By following the documentation, I have the below files: views.py from django.shortcuts import render # Create your views here. def base(request): articles = 'articles' dboard = 'dashboard' pages = {'dboard':dboard, 'Articles':articles} return render(request, 'collatedata/base.html', pages) def dash(request): return render(request, 'collatedata/dash.html') base.html: ... <li class="nav-item"> <a href="#" class="nav-link text-white p-3 mb-2"> <i class="fas fa-home text-light fa-lg mr-3"></i> {{ dboard }} </a> </li> ... dash.html {% extends "./base.html" %} however, the output does not read {{ dboard }} so returns this: <li class="nav-item"> <a href="#" class="nav-link text-white p-3 mb-2"> <i class="fas fa-home text-light fa-lg mr-3"></i> </a> </li> could it be to do with base.html being extended? -
Django handling second POST method inside view function
Im trying to find a way to post a submit as form auto filled with a scrape from a previous post method, so far Im trying inside the same function, cause I cant find a way to pass this scrape values to another view function, qwith this code it keeps asking me for the first value of the if statement, I kind of understand why the code fails, but I dont know how to approach it better def bus_rol(request): if request.method == 'POST': if request.POST['srh']: srch = request.POST['srh'] match = RolesSII.objects.filter(Q(rol__iexact=srch) | Q(dir__icontains=srch)) if match: pto = match[0] return render(request, 'd_data/busrrols.html', {'sr':match, 'pto':pto}) else: messages.error(request, 'No match') elif request.POST['srh_sii']: srch_sii = request.POST['srh_sii'] pars = parsing(srch_sii) p_form = roles_Form() if request.method == 'POST': p_form = roles_Form(request.POST) if p_form.is_valid(): p_form.limpiar() ficha_form = p_form.save(commit=False) ficha_form.save() return messages.success(request, f'Rol SII') else: pass return render(request, 'd_data/busrrols.html', {'pars':pars, 'form':p_form}) else: messages.error(request, 'No Rol') return render(request, 'd_data/busrrols.html') template <form method="POST"> <div class="row justify-content-md-center"> {% csrf_token %} <div class="text-center" style="margin-top:45px;"> <img src="{% static 'logo.png' %}" heigth="70" width="70"> <input class='form-control' style="margin-top:15px;"type="text" name="srh" placeholder="N° Rol o Dirección"> <button type="submit" class='btn btn-primary btn-block'>Buscar Rol Base I.M.A.</button> </div> <div class="text-center" style="margin-top:25px;"> <img src="{% static 'SII.png' %}" heigth="120" width="120"> <input class='form-control' style="margin-top:15px;"type="text" name="srh_sii" … -
Difference between ViewSet, ModelViewSet and APIView
What are the advantages of ViewSet, ModelViewSet and APIView. In the django-rest-framework documents it is not clear, it does not say when to use ViewSet, ModelViewSet and APIView. I want to implement an API that will have a business logic in there, a great business logic with data processing as well, what should be used for this case? I researched a lot and managed to understand a little about routers and urlpatterns but I didn't understand which one about views. -
DJANGO: add model via many-to-many field but edit its own fields before adding
I'm writing some kind of report-generator. The report consists of alerts, but each alert must be modified a little before I add it to report (some Alert fields depend on report). I have model Report: class Rep(models.Model): name = models.CharField(max_length=100) attributes = models.TextField() alerts = models.ManyToManyField(Alert) and model Alert: class Alert(models.Model): name = models.CharField(max_length=100) descriptions = RichTextField() recomendations = models.TextField() I have DJANGO form for creating a report: class NewRepForm(forms.ModelForm): class Meta: model = Rep fields = ('name', 'attributes','alerts') and it allows only add alerts to new report, without modifying them. How can I edit some fields of Alert itself before adding it to report? -
JSON data filtering Javascript (Nested dictionary and arrays)
everybody, I`m still new in JS and trying to figure out how js filter() works. If you help me asap, It would be great. I have an API, which is smth like this: [ { "name": "Category 1", "items": [ { "name": "Vacancy item #1", "location": "Los Angeles", "overview": "Lorem ipsum", "get_absolute_url": "/careers/vacancy-item-1/" }, { "name": "Vacancy item #2", "location": "Los Angeles", "overview": "Lorem ipsum", "get_absolute_url": "/careers/vacancy-item-2/" } ] }, { "name": "Category 2", "items": [ { "name": "Vacancy item #3", "location": "Washington D.C", "overview": "Lorem ipsum", "get_absolute_url": "/careers/vacancy-item-3/" } ] } ] I want to filter this data based on the select value of the form. I`m working on the VUE.JS and Django. And this is my JS code filteredItems() { let vacancycategories = this.listData, city = this.city, category = this.category if (city && city.length > 0) { vacancycategories = vacancycategories.filter((cat) => { cat.items = cat.items.filter((vacancy) => { return vacancy.location.indexOf(city) !== -1 }) return cat }) } if (category && category.length > 0) { vacancycategories = vacancycategories.filter((cat) => { return cat.name.indexOf(category) !== -1 }) } return vacancycategories } The category part is working as expected. But when I try to filter location fields it`s not working properly. The first … -
Data saved using a trigger (AFTER INSERT) in PostgreSQL is deleted when I use Django to save it
I'm working on a project using Django REST framework and PostgreSQL. 3 tables are involved, location, crime and location_crimes. The user can create a location using a postcode and the system find all the crimes that are inside that location (using an stored procedure) and saves them into the location_crimes table. I tested the trigger and the procedure directly in the DB and they work as expected. The problem is when I call one endpoint to create a new location. After the insert, I use a Django signal to print the data inserted using a raw query, just for testing. I discovered that the trigger works because I managed to return the data from that table with the expected result (with the inserted data returned from both tables). But when I check the database the information is not there, and the Dashboard from pgAdmin shows a DELETE is occurring right after the insert; (DB chart) I suspect there is a rollback or a commit not occurring but the pgAdmin dashboard doesn't show any problem. Thank you for your help. VIEW class LocationViewSet(viewsets.ModelViewSet): """Manage locations in the DB""" authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) queryset = Location.objects.all() serializer_class = serializers.LocationSerializer def … -
How do i use annotate to group the child models by the parent models?
I have 3 models. PeerReview Answer and Statement. A Peer review has many answers, Each answer belongs to a Statement (or question if you will) What I want is to get all answers from all PeerReviews grouped by their statements. So the end result should be a dictionary where there key is a statement object, and the value is a list of all the answers for that particular statement. If you would print it out it would look something like this: {Statement A : [answer, answer, answer], Statement B : [answer,answer,answer], Statement C : etc etc} I know that for group by queries i should use the annotate() method but all the examples i find are about count and sum actions. How do i use annotate to get the above mentioned dictionary as a result? Thank you -
Image layout acting weird after using django
So I am new to django and web development, and I am currently trying to build a blog site using django. I have downloaded this template.You can check out the original page from that link. After using DTL, and adding my own images in the posts part, the picture layout changes. The divider section (the image with stones) shrinks in width, even though I haven't touched it. I have added the {% static %} codes to that part as well. To solve this, I later added the original pictures to the posts again, but the divider is not going back to normal. Here is the code I have used: <section style="background: url({% static 'img/divider-bg.jpg' %}); background-size: cover; background-position: center bottom" class="divider"> <div class="container"> <div class="row"> <div class="col-md-7"> <h2>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</h2><a href="#" class="hero-link">View More</a> </div> </div> </div> </section> Is there anything wrong I have done here? Here is what it originally looked like enter image description here And here is what it looks like now enter image description here As you can see, the width reduced. The gap with the section above also reduce (none … -
How To Add Logout Required On Django Builtin login system
How To Add Logout Required on django builtin login system for example: if i'm logged in if i go to login url it open a login url i need to redirect on index if user is login Here is my urls.py from django.contrib import admin from django.urls import path,include from django.contrib.auth.views import LoginView,LogoutView urlpatterns = [ path('admin/', admin.site.urls), path('', include('basic.urls')), path('accounts/login/', LoginView.as_view(),name='login'), path('accounts/logout/', LogoutView.as_view(),name='logout'), ] Here is my views.py from django.shortcuts import render from .forms import UserForm,UserProfileInfoForm # Create your views here. def index(request): return render(request,'basic/index.html') def register(request): registered = False if request.method == "POST": user_form = UserForm(request.POST) profile_form = UserProfileInfoForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True else: print(user_form.errors,profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request,'basic/register.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered,}) -
Django DRF: @permission_classes not working
I have a view with a custom action which should have a custom permission "IsRightUser". However, the has_object_permission of it is never called, even though I try to access the object with self.get_object() in my view. class MyView(mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = MySerializer lookup_field = 'uuid' queryset = MyObject.objects.all() @action(methods=['get'], detail=True) @permission_classes([IsRightUser]) def groups(self, request, uuid=None): # prints [<class 'rest_framework.permissions.IsAuthenticated'>] print(self.permission_classes) my_object = self.get_object() groups = Group.objects.filter(my_object=my_object) serializer = MySerializer(groups, many=True) return Response(serializer.data) Here you can see my custom permission which is never called. class IsRightUser(BasePermission): def has_object_permission(self, request, view, obj): # never called return True When I use permission_classes = [IsRightUser] in my view (i.e. directly underneath the lookup_field) it works (unfortunately this is not feasible for me). Any help is very much appreciated. -
Django annotate subquery's aggregation
So I have three models class Advert(BaseModel): company = models.ForeignKey(Company, on_delete=CASCADE, related_name="adverts") class Company(BaseModel): name = models.CharField(max_length=50) class OrderRating(BaseModel): reported_company = models.ForeignKey(Company, on_delete=CASCADE, related_name='ratings') rating = models.DecimalField( max_digits=2, decimal_places=1, validators=[MinValueValidator(1.0), MaxValueValidator(5.0)], help_text='Rating from 1.0 to 5.0.' ) And I'm trying to get average of all order ratings related to the company and annotate that to the Advert model, when I do this: qs = Advert.objects.all().annotate( avg_rating=Subquery( OrderRating.objects.filter( reported_company=OuterRef('company')).aggregate(Avg("rating"))["rating__avg"] ) ) I get back stating This queryset contains a reference to an outer query and may only be used in a subquery.' Not sure where the problem is when I am calling the OuterRef inside a Subquery. -
Unittesting for django-channels
A'm beginner in django-channels. I'm use channels 2.3.1. I have following code. main routing websocket_urlpatterns = [ url(r'^ws/events/(?P<room_type>[^/]+)/(?P<room_id>[^/]+)/$', consumers.Consumer, name='core-consumer'), ] app routing application = ProtocolTypeRouter({ 'websocket': URLRouter(core.routing.websocket_urlpatterns), }) consumer class Consumer(AsyncWebsocketConsumer): async def connect(self): room_type = self.scope['url_route']['kwargs']['room_type'] room_id = self.scope['url_route']['kwargs']['room_id'] self.room_group_name = f'{room_type}_{room_id}' await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() async def receive(self, text_data = None, bytes_data = None): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.channel_layer.group_send(self.room_group_name, { 'type': 'send_data', 'message': message } ) async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_group_name, self.channel_name) async def send_data(self, event): message = event['message'] await self.send(text_data=json.dumps({ 'data': message })) def send_event(channel='', message=''): channel_layer = get_channel_layer() asyncio.run(channel_layer.group_send(channel, { 'type': 'send_data', 'message': message } )) signal def activate_notification(self): send_event(f'user_{self.id}', {'message': f"Welcome back to one deeds!"}) How can I test this with unittest? I read this documentation but nothing understand( I want to run test with command ./manage.py test I tried testing this with WebsocketCommunicator -
Notify webapplication user if others are viewing the same page
This is related to something we see on shopping sites. On some product pages we see that other n number of people are viewing the same product as you. Now I have to implement something like this using python-django and angular. If two users are accessing the same page, both should get the notification saying that other users are viewing the same page. is it possible? if yes, how it can be done? If any suggestion to implement it using any other technique? P.S. We do have user authentication. Thanks in advance. -
Django - DetailView - `get_object` function confusion
I'm new to CBV. Not sure why this isn't working... views.py class ItemDetailView(DetailView): '''display an individual item''' model = Item template_name = 'boutique/item.html' context_object_name = 'item' # With model specified, following code would be redundant, wouldn't it?? However... # def get_object(self): # return get_object_or_404(Item, pk=self.kwargs.get('item_pk')) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # add categories for navbar link texts context['categories'] = Category.objects.all() print('\ncontext= ', context, '\n') return context AttributeError at /item_8/ Generic detail view ItemDetailView must be called with either an object pk or a slug in the URLconf. And the context isn't being printed out. If I add get_object to the code, it's working fine: class ItemDetailView(DetailView): '''display an individual item''' # model = Item template_name = 'boutique/item.html' # context_object_name = 'item' def get_object(self): return get_object_or_404(Item, pk=self.kwargs.get('item_pk')) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # add categories for navbar link texts context['categories'] = Category.objects.all() print('\ncontext= ', context, '\n') return context However, if I changed get_object function to: def get_object(self): obj = super().get_object() obj = get_object_or_404(Item, pk=self.kwargs.get('item_pk')) # obj = obj.filter(pk=self.kwargs.get('item_pk')) # doesn't work, same error # obj = obj.get(pk=self.kwargs.get('item_pk')) # doesn't work, same error return obj ImproperlyConfigured at /item_8/ ItemDetailView is missing a QuerySet. Define ItemDetailView.model, ItemDetailView.queryset, or override ItemDetailView.get_queryset(). I'm … -
How can to test amazon api?
I have following code. How I can to test function create_items_by_parent_asin? def get_amazon(): return AmazonAPI(settings.AMAZON_ACCESS_KEY, settings.AMAZON_SECRET_KEY, settings.AMAZON_ASSOC_TAG) def get_item_by_asin(asin: str, response_group='Large'): amazon = get_amazon() product = amazon.lookup(ItemId=asin, ResponseGroup=response_group) return product def create_items_by_parent_asin(self, asin: str): amazon_item = get_item_by_asin(asin, response_group='Large') .... -
Using selenium in a dockerized environment: Executable needs to be in path
I am running a dockerized django app (cookiecutter-django). I want to get my browser tests with selenium to work. I normally test by doing docker-compose -f local.yml run django pytest. When I install selenium as a dependency and then run my tests I get Executable needs to be in path . Well it is in my path (installed it with homebrew and checked.) So I guess my docker env is not finding it. Then I added extra services like so without success: selenium_chrome: container_name: selenium_chrome image: selenium/node-chrome-debug environment: - HUB_PORT_4444_TCP_ADDR=selenium_hub - HUB_PORT_4444_TCP_PORT=4444 ports: - "5900:5900" depends_on: - selenium_hub I don't know want anymore containers than necessary but I wanted to troubleshoot. But I still get the error. Does anyone know how docker handles path variables or how I could fix this error? I just want to execute my tests and add browser tests to it, best case, without more images and containers. Is that even possible? Thanks for every help! Greatly appreciated! -
How to declare a auto-incrementing alphanumerical id field with predefined aplphabetic part (Django python)
I am developing an app in Django. I want to insert in my model an auto-incrementing alphanumerical ID field, having, by default, a fixed alphabetical part and an auto-incrementing numerical part. But I also want the availability to change, from admin section, this id to another alphanumerical one, with a different alphanumerical and numerical part. Example: Desired alphabetical constant part: ITM Desired numerical auto-incrementing part: 00000 So that every object of my model, when generated, get default progressive values like: ITM00001, ITM00002, ITM00003, ... I would like to change the field value from my admin section into, for example: ABC0000001, DFG0051, RST034, ... Max field length: 10 I realize that I have to use AutoField and to somehow join the constant string with the auto-incrementing numerical variable, but I don't know how to do it. class my_model(models.Model): Field_1 = models.CharField(max_length=10, blank=True, null=True) static_ID = models.AutoField(???) -
Django many to many relation with admin panel display
I want to do a many to many relation in Django and display a list of variables in the admin panel. I found the documentation a little bit complicated to understand and I am unable to make this work. This are my files: models.py class LanguageFramework(models.Model): name = models.CharField(max_length=200,blank=False, null=False) def __str__(self): return(str(self.name)) class Project(models.Model): name = models.CharField(max_length=200, blank=False, null=False) languages_frameworks = models.ManyToManyField(LanguageFramework) description = models.TextField(max_length=10000, blank=False, null=False) github_link = models.CharField(max_length=400, blank=False, null=False) post_link = models.CharField(max_length=400, blank=False, null=False) class ProjectsGotFrameworks(models.Model): project_id = models.ForeignKey(Project, on_delete=models.CASCADE,default=None) language_framework_id = models.ForeignKey(LanguageFramework, on_delete=models.CASCADE,default=None) admin.py class ProjectAdmin(admin.ModelAdmin): search_fields = ['name','languages_frameworks'] list_display = ('name','languages_frameworks') filter_horizontal = ('languages_frameworks') fieldsets = [ ('Project info',{'fields': ['name','description']}), ('External',{'fields': ['github_link','post_link']}), ('Media',{'fields': ['image_1','image_2','image_3','image_4','image_5']}), ] So what I want, is to display a list of all LanguagesFrameworks elements in the ProjectAdmin page and let me select which ones of the list are in one project. Thank you in advance. -
Filtering warnings in django tests
I'm trying to make some warnings thrown by django be raised as errors in my unit tests. I've configured my test settings this way: from warnings import filterwarnings from django.core.paginator import UnorderedObjectListWarning filterwarnings('error', category=UnorderedObjectListWarning) When I run my test on one application, the warning is correctly raised as an exception. But if I run my test globally, no exception is raised. ./manage.py test myapp # warnings are raised as exception ./manage.py test # no exception Why do I have this difference and how can I manage to have warnings raised as exception when running all my tests ? -
How can I improve pagination performance in multiple queryset django?
I have 2 queryset : queryset_primary = PrimaryUserSerializer(FileUpload.objects.all().order_by('name'), many=True, context=context).data queryset_secondary = MemberSerializer(Members.objects.all().order_by('member_name'), many=True, context=context).data Both having different keys ..so that I iterated both querysets : response = [] for primary in queryset_primary: # name_pri=primary['primary_user_id'] new_data={ 'user_id' : primary['primary_user_id'], 'name': primary['name'], } response.append(new_data) for secondary in queryset_secondary: new_data={ 'user_id' : secondary['secondary_user_id'], 'name': secondary['member_name'], } Again I used a common serializer having similar keys in it, for pagination : responses = self.paginate_queryset(response) if responses is not None: serializer = CommonUserSerializer(responses,many=True) data = { 'code': 200, 'status': "OK", } page_nated_data = self.get_paginated_response(serializer.data).data data.update(page_nated_data) data['response'] = data.pop('results') return Response(data) It totally taking 8 seconds of loading time. How can I reduce the API loading time ?