Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make all Hyperlinks in Django REST Framework relative?
Is there any easy way to use relative to Root urls instead of absolute ones? By default DRF returns something like this: { "url": "http://127.0.0.1:34503/items/4/", ... "parent": "http://127.0.0.1:34503/items/1/", "stargazers": "http://127.0.0.1:34503/items/4/stargazers", } I would like it to be: { "url": "/items/4/", ... "parent": "/items/1/", "stargazers": "/items/4/stargazers", } Any ideas? I am using HyperlinkedModelSerializer: class ItemSerializer(serializers.HyperlinkedModelSerializer): stargazers = serializers.HyperlinkedIdentityField(view_name='item-stargazers') class Meta: model = Item fields = ['url', 'id', ..., 'stargazers'] -
Multiple choices are not saving in Dango admin
I am building a BlogApp and I am storing user's multiple interest in a CharField. I have used multiple select field in html. Choices are showing fine BUT when i try to save multiple values at a time then only one is adding. models.py class Profile(models.Model): full_name = models.CharField(max_length=30) interests = models.CharField(max_length=30) template.html <div class="container-fluid"> <div class="row"> {% csrf_token %} <br> <br> <input type="text" name="full_name"> <label for="interests">Choose a car:</label> <select name="interests" id="interests" multiple> <option value="cricket">Cricket</option> <option value="piano">Piano</option> <option value="eating">Eating</option> </select> <div class = "col text-center"> <input type="submit" class="btn btn-primary" value="Save Name" /> </div> </div> <form> </div> When i try to select more than one interest and check admin then it is showing only one interest. Any help would be much Appreciated. Thank You in Advance. -
filter articles for category in Dango
Very good, I am doing a personal blog as the first project in the world of web development, which I am developing with django, but I have a problem, the truth is I cannot find a way to filter my articles by categories, I show you my viewed models. I have seen some examples using foreign keys but that causes me that the articles can only have a single category. I understand that to get the articles by categories I have to do a "fiilter" of categories but I even got there, if someone could guide me I would appreciate it very much class Article(models.Model): title = models.CharField(max_length=150, verbose_name='Titulo') subtitle = models.CharField(max_length=50,default='Máximo 50 carácteres, que no se te olvide' ,verbose_name='subtitulo') content = RichTextField(verbose_name="Contenido") image = models.ImageField(default="null", verbose_name="Imagen", upload_to = "media") user = models.ForeignKey(User, verbose_name="Usuario", on_delete=models.CASCADE, editable=False) categories = models.ManyToManyField(Category, verbose_name="Categorias") create_at = models.DateTimeField(auto_now_add=True, verbose_name="Creado el") update_at = models.DateTimeField(auto_now=True, verbose_name="Editado el") def __str__(self): return self.title class Meta: verbose_name = ('Articulo') verbose_name_plural = ('Articulos') ordering = ['id'] class Category(models.Model): name = models.CharField(max_length=100, verbose_name="Nombre") description = models.CharField(max_length=255, verbose_name="Descripcion") create_at = models.DateTimeField(auto_now_add=True, verbose_name="Creado el") def __str__(self): return self.name class Meta: verbose_name = ('Categoria') verbose_name_plural = ('Categorias') /views: def article(request, article_id): article = get_object_or_404(Article, id=article_id) … -
Parsing data-dict vs. model-instance to Django ModelForm
Is there a difference between doing instance = MyModel() form = MyModelForm(instance=instance) form.save(commit = False) form.instance.foo="foo" form.instance.bar="bar form.save() and data = {"foo":"foo","bar":"bar"} form = MyForm(data=data) form.save() when creating an object? -
Razorpay customize Payment options ( more than one option ) in django
I am using razorpay in a django project. I want customized payment methods ( not only one, but more than one options ). To be more specific, I want something like data-prefill.method = 'netbanking/upi' I want this two netbanking and UPI payment options only. I found something like "options": { "checkout": { "method": { "netbanking": "1", "upi": "1", "card": "0", "wallet": "0" } } } But how to implement this on django template? Thanks in advance, Hasnain -
How can I get a GraphQL query to respond with an array of multiple object types? I'm using Django GraphQL API using Graphene
I have a Django GraphQL API (using Graphene) that I am using to build a chat app. The app allows for either one to one chat or a group chat and in the UI (Angular-based), there is a single search bar. So when a user enters a search query, I would like to show them all of the following in a single list:- Members who's first or last name contain the query Group chats whose name contain the query Individual chat messages that contain the query Here are the models:- class Group(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=250) institution = models.ForeignKey(Institution, on_delete=models.PROTECT) avatar = models.CharField( max_length=250, blank=True, null=True, default="https://i.imgur.com/hNdMk4c.png") searchField = models.CharField(max_length=400, blank=True, null=True) # Type Choices class TypeChoices(models.TextChoices): CLASS = "CL", _('Class') TEAM = "TE", _('Team') COORDINATiON = "CO", _('Coordination') # End of Type Choices group_type = models.CharField( max_length=2, choices=TypeChoices.choices, default=TypeChoices.TEAM) admins = models.ManyToManyField(User, related_name="adminInGroups", through="GroupAdmin", through_fields=( 'group', 'admin'), blank=True) members = models.ManyToManyField( User, related_name="memberInGroups", through='GroupMember', through_fields=('group', 'member'), blank=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class GroupAdmin(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) admin = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.group class GroupMember(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) member = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return … -
HttpResponseRedirect(reverse) and render
I am a rookie in Django and find that I don't quite understand two commands: HttpResponseRedirect(reverse) and render, though I have read official documentation a couple of times. I have two questions: what's the difference between HttpResponseRedirect and render? I usually use HttpResponseRedirect when it returns the result that I expect. Otherwise, I will use render. Though it did work sometimes, I still think that my understanding is probably incorrect. Another question is that why we always need reverse together with HttpResponseRedirect? In what circumstance I should use HttpResponseRedirect without reverse? Thanks in advance for your help. -
Connect django to Google Cloud SQL?
I am trying to migrate my db from sqlite3 to cloud sql but im getting some error DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', 'ENGINE': 'django.db.backends.mysql', 'HOST': 'IP_OF_MY_SQL_INSTANCE', 'PORT': '3306', 'NAME': 'CONNECTION_NAME', 'USER': 'ROOT_USER', 'PASSWORD': 'ROOT_USER_PASSWORD' # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Are these correct as the tutorial does not have proper way to configure for MySql and Django https://cloud.google.com/python/django/appengine#configuring_the_database_settings I am getting this error django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'MY_IP' (10060)") Can anyone help me out? Thanks -
How to make a unique URL for each user in Django?
I am making website with Django. I want each user to have their own URL, so if a user with the username "john" registers, the URL will be .../user/john or if a user with the username "tim" registers, the URL will be .../user/tim. I also want that when I log in as "tim" and enter .../user/john in the search, I will see John's page. This is my urls.py file: from django.contrib import admin from django.urls import path, include from webapp.views import welcome_page, register, user_page, settings, timeline urlpatterns = [ path('admin/', admin.site.urls), path("", welcome_page, name="welcome_page"), path("register/",register, name="register" ), path("", include("django.contrib.auth.urls"), name="login_logout"), path("user/",user_page, name="user_page"), path("settings/", settings, name="settings"), path("main/", timeline, name="main_timeline"), ] And this is my views.py file: from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect from .forms import RegisterForm from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User def welcome_page(response): return render(response,"welcome.html") def register(response): error = "" if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): form.save() return redirect("/login") else: error = form.errors form = RegisterForm() return render(response, "register/register.html", {"form":form, "error" : error}) @login_required def user_page(response): username = str(User.objects.get(username=response.user.username)) userphoto = username[0:2] return render(response, "user_page.html", {"userphoto": userphoto}) @login_required def settings(response): return render(response, "settings.html") @login_required def timeline(response): return render(response, "timeline.html") -
Show quantity based on chosen part name from dropdown
I was following this method to show the part quantity after choosing the part from the dropdown. To make it happen I created two tables Part and Order where Part is FK in the Order table. So whenever, the user chooses the part name in the Order form, then show the part quantity of that selected part. I am trying to solve it by using js, but I need help. The following picture from Order form. So choose the Part Name and then show that quantity into the Part Quan box. models.py class Order(models.Model): part = models.ForeignKey(Part, on_delete=models.CASCADE) qu = models.DecimalField(max_digits=10,decimal_places=2) class Part(models.Model): partname = models.CharField(max_length=50) quan = models.PositiveIntegerField(default= 0) Views.py def create_order(request): from django import forms form = OrderForm() if request.method == 'POST': for form_data in forms_data: forms = OrderForm(request.POST) if forms.is_valid(): product = forms.cleaned_data['product'] part = forms.cleaned_data['part'] qu = forms.cleaned_data['qu'] order = Order.objects.create( product=product, part=part, qu=qu, ) return redirect('order-list') context = { 'form': form } return render(request, 'store/addOrder.html', context) def fetch_quan(request, pk): part = get_object_or_404(Part, pk=pk) print('part',part) if request.method=='GET': response = HttpResponse('') quan = part.quan print('quan',quan) response['quan-pk'] = part.pk response['quan'] = quan return response URL url(r'^quan/(?P<pk>\d+)$', views.fetch_quan, name='fetch_quan'), HTML <form action="#" method="post" id="form-container" novalidate="novalidate"> {% csrf_token %} <div … -
Get non-valid fields from Django Form
Say I have the following view def add_list(request): user = request.user if request.method =="POST": instance = MyModel(user=user) form = MyForm(instance = instance) form.is_valid() #False is there a way to figure out, which fields are "wrong" and why? I tried form.errors which returned {} -
How to update model in Django using kwargs
I am writing update method for my model: class Task(models.Model): @staticmethod def update_task(task_id: int, calendar_path: str, **kwargs): cal = get_object_or_404(Calendar, path=calendar_path) task = get_object_or_404(Task, id=task_id) if task.calendar != cal: raise FieldError("Calendar does not contains this task") for field_name, value in kwargs: task I want all fields from kwargs to be renamed, for example like this: update_task(..., name = "New Name", description = "New description") But I have no idea how to do it, without of using eval, but that is not good idea. -
How do I display a date in a top of chat message with django
I want to do something like what is talking about in this post (How do I display the calendar date on the top of chat messages?) but in Django. Somebody can actually help me?? -
How to count number of product within category in django
Actually i want to count number of coupons ( product ) within stores (category) and show them in stores nothing but index.html page. Here is my models.py class stores(models.Model): stores_name = models.CharField(max_length=50) slug = models.CharField(max_length=25, default=randomString , unique = True) .....(some stores info ) def get_absolute_url(self): return reverse('Stores:couponstores', args=[str(self.slug)]) class coupon(models.Model): cfid = models.ForeignKey(stores, on_delete=models.CASCADE) cname = models.CharField(max_length = 100) ....(some coupons info ) def get_absolute_url(self): return reverse('Stores:coupon',args=[self.id,]) Views.py def index(request): stores = stores_model.objects.all() context = {'stores': stores} return render(request,'Stores/index.html', context) def coupons(request,stores_slug=None): St = None allstores = stores_model.objects.all() allcoupons = coupon_model.objects.all() if stores_slug: St = get_object_or_404(stores_model , slug=stores_slug ) allcoupons = allcoupons.filter(cfid = St) return render(request,'Stores/coupons.html', {'allcoupons':allcoupons,'allstores':allstores,'St':St,}) def coupon_details(request,id): allcoupons = get_object_or_404(coupon_model , id=id) return render(request,'Stores/coupons.html',{'allcoupons':allcoupons}) Here my templates index.html {% for i in stores %} <p>{{i.stores_title}}</p> <p>{{i.sdesc}}</p> <p>(here i want to show number of product)</p> <button>all coupons</button> {%endfor%} coupons.html If someone clicks on stores button this page will be shows. ...... Thanks in advanced -
django listview pagination is too slow on large dataset
I have a django listview that shows filtered data from Catalogue. It works fine on small database, but when database is too large, it takes too long time to return results. views.py: class all_ads(generic.ListView): paginate_by = 12 template_name = 'new_list_view_grid-card.html' def get_queryset(self): city_district = self.request.GET.getlist('city_district') usage = self.request.GET.get('usage') status = self.request.GET.get('status') last2week = datetime.datetime.now() - datetime.timedelta(days=14) status = status.split(',') if usage: usage = usage.split(',') else: usage = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] intersections = list(set(status).intersection(usage)) type_q = (Q(type__in=intersections) & Q(type__isnull=False)) cat_ids = list(models.Catalogue.objects.filter( Q(*[Q(city__contains=x) for x in city_district], _connector=Q.OR) | Q(*[Q(district__contains=x) for x in city_district], _connector=Q.OR) ).values_list('pk', flat=True)) result = models.Catalogue.objects.filter( Q(datetime__gte=last2week), type_q, pk__in=cat_ids ).distinct().order_by('-datetime').prefetch_related('type') return result models.py: class Catalogue(models.Model): city = models.CharField(db_index=True,max_length=100, null=True) district = models.CharField(db_index=True,max_length=100, null=True) type = models.ManyToManyField(Type, db_index=True) class Type(models.Model): name = models.CharField(max_length=100, db_index=True) def __str__(self): return self.name And this is template.html: {% for Catalogue in catalogue_list %} "do something" {% endfor %} -
Django Broken Pipe Message
When creating an instance in Django Admin, I get the 'Broken pipe' message in the terminal. The instance can be seen in Django Admin and everything seems to be okay. Is this something that I can ignore or is there something wrong with my models? models.py from django.db import models from django.urls import reverse from django.utils.translation import gettext_lazy as _ from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField( verbose_name=_("Category"), max_length=255, unique=True, ) slug = models.SlugField(verbose_name=_("Category URL"), max_length=255, unique=True) parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children") class MPTTMeta: order_insertion_by = ["name"] class Meta: verbose_name = _("Category") verbose_name_plural = _("Categories") def get_absolute_url(self): return reverse("store:category_all", args={self.slug}) def __str__(self): return self.name class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.RESTRICT) title = models.CharField( verbose_name=_("title"), max_length=255, ) description = models.TextField(verbose_name=_("description"), blank=True) slug = models.SlugField(max_length=255) price = models.DecimalField( verbose_name=_("Price"), max_digits=5, decimal_places=2, ) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) class Meta: verbose_name = _("Product") verbose_name_plural = _("Products") def get_absolute_url(self): return reverse("store:prod_details", args=[self.slug]) def __str__(self): return self.title Terminal [03/Jul/2021 12:29:24] "POST /admin/store/category/add/ HTTP/1.1" 302 0 [03/Jul/2021 12:29:24] "GET /admin/store/category/ HTTP/1.1" 200 8094 [03/Jul/2021 12:29:24] "GET /admin/jsi18n/ HTTP/1.1" 200 3195 [03/Jul/2021 12:29:24] - Broken pipe from ('127.0.0.1', 67866) -
Django - The current path, job/all, matched the last one. - But it still returns 404
When I go to this URL http://127.0.0.1:8000/job/all I am always receiving a 404 error with this message: 404 Django Error screenshot However, when I just go to http://127.0.0.1:8000/ or http://127.0.0.1:8000 it always finds the / (index) route correctly regardless if there is a trailing slash, or not. This issue seems to only happen with the /job/WHATEVER_ELSE_GOES_HERE URLs. I have the following URLs setup: My jobs app urls.py: from django.urls import path from .views import * urlpatterns = [ path('', index, name="index"), path('job/<int:job_id>', job_details, name="job_detail"), path('job/all/', all_jobs, name="all_jobs"), path('job/add/', add_job, name="add_job"), path('job/my_posted_jobs/', my_posted_jobs, name="my_posted_jobs"), path('job/delete/<int:job_id>', delete_job, name="delete_job"), path('job/search', search_job, name="search_job"), path('job/apply_for_job/<int:job_id>', apply_for_job, name="apply_for_job") ] My project's urls.py: from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('jobs.urls')), path('user/', include('users.urls')), path('payments/', include('payments.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In the error message (screenshot) it also says this: The current path, job/all, matched the last one. How come it matches a URL but returns 404? How do I fix it? Thank you -
@permission_required decorator returns no user attribute in View error
I'm working with Django-admin panel. I have created a custom view file to add a file manager. To make file uploading safe, I just added permission_required decorator. But it throws an error 'FileBrowser' object has no attribute 'user'. Here is my code. class FileBrowser(ListView): model = File paginate_by = 30 template_name = "file_manager/browser.html" extra_context = { 'file_type': type, 'title': "Media Browser", } @permission_required('file_manager.view_file') def dispatch(self, request, *args, **kwargs): file_type = request.GET.get('type') self.queryset = File.objects.filter(type=file_type) self.extra_context['value_to'] = request.GET.get('value_to') self.extra_context['image_to'] = request.GET.get('image_to') self.extra_context['form'] = FileForm() return super().dispatch(request, *args, **kwargs) -
Django href pass multiple parameters to function
I want to pass two parameters from an HTML page throw href to a function first the parameter are: HTML page, {{object.id}} . . {% for item in model_items %} <td>{{item.ID}}</td> <td class="p-1 mb-1 text-dark"> <a href="{% url 'Up_Items' item.id {{object.id}} %}" class="btn btn-info btn-sm">Add Item</a></td> and the second thing is the urls.py; path('Up_Items/<int:id_itm,id_itm2>/', views.ADD_item, name='Up_Items'), and the function in views.py. def ADD_item(request, id_itm, id_itm2): print(id_itm, id_itm2 ) return redirect('Invoices') what I missed here to work correctly plseae? -
what is the meaning of this error-django webframework
[03/Jul/2021 12:37:09] "GET /Calculatorapp HTTP/1.1" 200 2941 [03/Jul/2021 12:37:09] "GET /static/logo.jpg HTTP/1.1" 404 1783 -
Why do I get 'illegal multibyte sequence' error when installing zappa?
so I'm trying to use AWS lambda for my Django project, and learned that I needed zappa. I was following the official guide, tried pip install zappa, then ran into an error message saying "'cp949' codec can't decode byte 0xe2 in position 2339: illegal multibyte sequence". Full error message is this: File "<string>", line 1, in <module> File "C:\Users\user\AppData\Local\Temp\pip-install-4iwakfy4\kappa_5a4d7eb77b754bf2888ab086b2876cb0\setup.py", line 54, in <module> run_setup() File "C:\Users\user\AppData\Local\Temp\pip-install-4iwakfy4\kappa_5a4d7eb77b754bf2888ab086b2876cb0\setup.py", line 22, in run_setup long_description=open_file('README.rst').read(), UnicodeDecodeError: 'cp949' codec can't decode byte 0xe2 in position 2339: illegal multibyte sequence``` <br><br> Any idea on why this occurs? Thank you very much in advance. -
Sendind email after receiving data from POST in Django
I want that the user fills a form (made using Django Model Forms) then receive the data from POST and send a copy though gmail using django send_mail function. Here is my settings.py configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = 'anyone@gmail.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_PASSWORD = '' Here is my views.py def GetOrder(request): mymodalform = MyOrderForm(request.POST) if mymodalform.is_valid(): # Save in DB mymodalform.save() # Send a copy via gmail to anyone@gmail.com email_subject = 'Order Credentials/Information from ' + mymodalform.name # email_body = "Congratulations if you receive this email, then your order is already in treatment. Below are the order information..." + "Name : " + MyOrderForm.Name + "Phone Number : " + MyOrderForm.Phone + "Email Address : " + MyOrderForm.Email + "Additional Information : " + MyOrderForm.AdditionalInfo + "Ordered pamphlet : " + MyOrderForm.Product + "Number of copies ordered : " + MyOrderForm.Amount #email_body = mymodalform.Product from_email = 'anyone@gmail.com' to_emails = ['anyone@gmail.com'] send_mail( email_subject, mymodalform.split(','), from_email, to_emails, fail_silently=False ) # Flash message to confirm order placement. messages.add_message( request, messages.SUCCESS, 'Your order was placed successfully! We\'ll soon contact you to confirm the order.' ) return redirect('Order') Here is my forms.py class MyOrderForm(forms.ModelForm): #Metadata class Meta: model … -
Consulta para acceder a los datos de un contexto en django [closed]
Estoy intentando acceder a los datos de una variable generada de la siguiente forma: enter image description here Luego quise desplegarla en mi template, pero no sé cómo acceder a cada dato, por ejemplo acceder uno de la tabla TrabajoRealizado y también acceder a algún dato de la tabla Mecanico. Había intentado la siguiente sintaxis (la cuál está mala por supuesto): enter image description here Adjunto los modelos de ambas tablas para mayor comprensión. De antemano, muchas gracias: class TrabajoRealizado(models.Model): id_trabajo = models.IntegerField( primary_key = True, verbose_name = "Id trabajo realizado", null = False, blank = False ) tipo_trabajo = models.CharField( max_length = 50, verbose_name = "Tipo de trabajo", null = False, blank = False ) mecanico = models.ForeignKey( Mecanico, on_delete=models.CASCADE, verbose_name = "mecanico", null = False, blank = False ) vehiculo = models.ForeignKey( Vehiculo, on_delete=models.CASCADE, verbose_name = "vehiculo", null = False, blank = False ) mas_informacion = models.CharField( max_length = 100, verbose_name = "Mas informacion", null = False, blank = False ) foto_trabajo = models.ImageField(upload_to = "fotosTrabajosDB") def __str__(self): return self.tipo_trabajo class Mecanico(models.Model): id_mecanico = models.IntegerField( primary_key = True, verbose_name = "Id mecanico", null = False, blank = False ) nombre_mecanico = models.CharField( max_length = 50, verbose_name = "Nombre … -
Navigation bar image is not loading
I am trying to add logo to my navigation bar but the image is not loading. code is as showing below, <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="/"><img src="PVPLogo.PNG" width="40" height="40" class="d-inline-block align-top"></a> <a class="navbar-brand" href="/"><h2>Electronic shop</h2></a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="true" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> </div> </nav> I added my image in the App > Images folder > PVPLogo.PNG All I can see is -
django - improve performance of __in queryset in M2M filtering
I have a models that has a M2M relationship to another model. These are my models: class Catalogue(models.Model): city = models.CharField(db_index=True,max_length=100, null=True) district = models.CharField(db_index=True,max_length=100, null=True) type = models.ManyToManyField(Type, db_index=True) class Type(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name And this is views.py: class all_ads(generic.ListView): paginate_by = 12 template_name = 'new_list_view_grid-card.html' def get_queryset(self): city_district = self.request.GET.getlist('city_district') usage = self.request.GET.get('usage') status = self.request.GET.get('status') last2week = datetime.datetime.now() - datetime.timedelta(days=14) status = status.split(',') if usage: usage = usage.split(',') else: usage = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] intersections = list(set(status).intersection(usage)) type_q = (Q(type__in=intersections) & Q(type__isnull=False)) result = models.Catalogue.objects.filter( Q(datetime__gte=last2week) & type_q & ((reduce(operator.or_, (Q(city__contains=x) for x in city_district)) & Q(city__isnull=False)) | (reduce(operator.or_, (Q(district__contains=x) for x in city_district)) & Q(district__isnull=False))) ).distinct().order_by('-datetime').prefetch_related('type') return result I want to filter MySQL db with some queries and return result in a listview. It works good on a small database, but with large database it takes over 10 seconds to return results. If I delete type_q query, It takes 2 seconds (reduce 10 second!). How can I improve performance of __in queryset?