Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
S3ResponseError: 403 Forbidden on some operations
I'm getting an "S3ResponseError: 403 Forbidden" from some boto 2.49.0 operations that were previously working. I seem to be able to put objects, and get them, but not delete or download. For example: import boto s3 = boto.connect_s3('my_key', 'my_secret') bucket = s3.lookup('my_bucket_name') key = bucket.new_key('testkey') key.set_contents_from_string('This is a test') key.exists() This works, and key.exists() returns True. I can see the new testkey file in my bucket the AWS console. key.delete() returns S3ResponseError: 403 Forbidden, and so does downloading it: with open('gettestkey', 'wb') as f: key.get_contents_to_file(f) The policy attached to the IAM user whose creds I'm using includes: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::my_bucket_name", ] }, { "Effect": "Allow", "Action": [ "s3:PutObject", "s3:PutObjectAcl", "s3:GetObject", "s3:GetObjectAcl", "s3:DeleteObject" ], "Resource": [ "arn:aws:s3:::my_bucket_name/*", ] } ] } I've seen inconsistencies between server times mentioned as a possible cause, but the time on my local Docker instance (where I'm running the above) seems correct. What am I missing? What could have changed - either codebase or on bucket - to cause those operations to now fail? -
Cannot upload user profile picture
I would like to allow a user to upload a profile and for the profile uploaded to be updated as the user's new profile picture. I have tried following a tutorial I found on YouTube and read some answers on stackoverflow but still struggling. This is what I have in forms.py: # edit mentor profile class MentorProfileForm(forms.ModelForm): class Meta: model = User exclude = ('password',) def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: w,h = get_image_dimensions(avatar) #validate size max_width = max_height = 100 if w > max_width or h > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' %(max_width,max_height)) #validate content type main, sub = avatar.content_type.split('/') if not (main == 'image' and sub in ['jpeg','pjpeg','gif','png']): raise forms.ValidationError(u'Please use a JPEG, ' 'GIF or PNG image.') #validate file size if len(avatar) > (20 * 1024): raise forms.ValidationError( u'Image file must not exceed 20k.' ) except AttributeError: pass return avatar The idea here being to allow users to only upload images of a certain size so I do not have to resize profile pictures models.py: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) ... class Mentor(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) linkedin = models.URLField(max_length=200,null=True,blank=True) photo = models.ImageField(null=True,blank=True,upload_to='media') def … -
Django1.2/google-appengine debug "KeyError: 'REQUEST_METHOD" Error
I have a python 2.7 project that uses both Django 1.2 and google-appengine. To run the file i type "python main.py." In doing so, i get the following error. I am not fammiliar with either google-appengine or Django to know why i am getting this error. 2. Also the project has a folder called 'lib' which has a folder in it called 'appengine.' I tried to set a path to this folder but it seems to do nothing. Traceback (most recent call last): File "/home/vicktree/.local/share/virtualenvs/noahs-app-M81YxnJh/local/lib/python2.7/site-packages/webapp2.py", line 1535, in __call__ rv = self.handle_exception(request, response, e) File "/home/vicktree/.local/share/virtualenvs/noahs-app-M81YxnJh/local/lib/python2.7/site-packages/webapp2.py", line 1595, in handle_exception return handler(request, response, e) File "/home/vicktree/Desktop/noah/web/noahs-app/handlers/hoptoad_handler.py", line 82, in handle_500_error notify_hoptoad(exception, request, False, False) File "/home/vicktree/Desktop/noah/web/noahs-app/handlers/hoptoad_handler.py", line 76, in notify_hoptoad send_to_hoptoad(generate_xml(exn, request, debug_mode), use_ssl) File "/home/vicktree/Desktop/noah/web/noahs-app/handlers/hoptoad_handler.py", line 34, in generate_xml xml << ('url', request.url) File "/home/vicktree/.local/share/virtualenvs/noahs-app-M81YxnJh/local/lib/python2.7/site-packages/webob/request.py", line 495, in url url = self.path_url File "/home/vicktree/.local/share/virtualenvs/noahs-app-M81YxnJh/local/lib/python2.7/site-packages/webob/request.py", line 467, in path_url bpath_info = bytes_(self.path_info, self.url_encoding) File "/home/vicktree/.local/share/virtualenvs/noahs-app-M81YxnJh/local/lib/python2.7/site-packages/webob/descriptors.py", line 70, in fget return req.encget(key, encattr=encattr) File "/home/vicktree/.local/share/virtualenvs/noahs-app-M81YxnJh/local/lib/python2.7/site-packages/webob/request.py", line 153, in encget raise KeyError(key) KeyError: 'PATH_INFO' ERROR:root:'REQUEST_METHOD' Traceback (most recent call last): File "/home/vicktree/.local/share/virtualenvs/noahs-app-M81YxnJh/local/lib/python2.7/site-packages/webapp2.py", line 1546, in __call__ return response(environ, start_response) File "/home/vicktree/.local/share/virtualenvs/noahs-app-M81YxnJh/local/lib/python2.7/site-packages/webob/exc.py", line 358, in __call__ is_head = environ['REQUEST_METHOD'] == 'HEAD' KeyError: 'REQUEST_METHOD' … -
Returning a dictionary inside a Django view
I have the following view: def myView(request): mydict = {} if request.method == 'POST': data = request.POST for key in data.items(): mydict.update({key[0]: key[1]}) print('FIRST:', mydict) print('SECOND':, mydict) return JsonResponse(mydict) So, a POST request is received. The POST request contains a dictionary, like this: {'one': 1, 'two': 2}. After this dictionary is received, my code should take that dictionary and update it to the variable mydict. So the final output of mydict should be {'one': 1, 'two': 2}. If i try print(mydict) here is what happens when the view is called: FIRST: {'data': '1', 'two': '2'} SECOND: {'data': '1', 'two': '2'} [08/Jan/2020 16:54:27] "POST /myView/ HTTP/1.1" 200 25 SECOND: {} If i go to the HTML page of this view, i will see an empty dictionary, instead of seeing '{'one': 1, 'two': 2}'. Can someone tell me what's happening here? Why is the dict being printed three times when the POST request is received? And why is the dictionary empty, when returned from the view? Thanks in advance! -
How to create signup form for Custom User from CustomUser model with added extra field
I am working on implementation of custom user app into my project because built-in django auth didnt appropriate for me. Following code i partially was took from official django documentation. I created MyUser model from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ from .managers import CustomUserManager class MyUser(AbstractBaseUser): username = models.CharField(max_length=40,null=True) email = models.EmailField(_('email adress'),unique=True) date_joined = models.DateTimeField(auto_now_add=True,null=True) last_login = models.DateTimeField(auto_now=True, null=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email def has_perm(self,perm,obj=None): return True def has_module_perms(self,app_label): return True @property def is_stuff(self): return self.is_admin I also have Managers.py file where instantiated from django.contrib.auth.models import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): def create_user(self,email,password=None,**extra_fields): """ Create and save user with the given email and password """ if not email: raise ValueError(_('The email must be set')) email = self.normalize_email(email) user = self.model(email=email,**extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,password,**extra_fields): """ Create and save SuperUser with the given email and password """ extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) extra_fields.setdefault('is_active',True) user = self.create_user(email=self.normalize_email(email),password=password,**extra_fields) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) user.save(using=self._db) return … -
Should I use multithreading or celery?
I'm developing a web app using django framework. I want to handle large amount of traffic. But I'm confused should I use celery or multithreading. Suppose 100k or more user request for same detail page or list page at same time So in this case celery is best or multithreading. Why? -
How to pass a request.user to a model Manager?
I have a model manager with a get_queryset: class BookManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(author=self.request.user This results in the error: AttributeError: 'BookManager' object has no attribute 'request` I understand managers are "request-unaware". How would I make a method in your manager/queryset that takes a parameter for the request.user? -
Django Signal Profile Creation Issue
I created a user profile section on my application and im trying to implement automatic creation of a profile when a user creates an account on my registration page, but ever since i added the signal and receive functionality, im getting the following error now. invalid literal for int() with base 10: '' Here is my views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from users.forms import UserRegisterForm from django.core.mail import send_mail def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account {username} has been created, you can now login !') return redirect('login') else: form = UserRegisterForm() messages.warning(request,(form._errors)) return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): return render(request, 'users/profile.html') @login_required def dashboard(request): return render(request, 'users/dashboard.html') Signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() Traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 2.2.9 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'forms.apps.FormsConfig', 'crispy_forms', 'users.apps.UsersConfig', 'points.apps.PointsConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File … -
How can I add a Bar Chart to my Django based Database?
Dear community members, I really hope that you will help me to add a Bar Graph to my Django project. 1. I have a Database with around 1000 items. 2. I need to be able visualise a 3 month sales for each item when needed. Not sure what is a correct approach. here is my models.py: from django.db import models from math import * from decimal import * class Itemslist(models.Model): item_n = models.CharField(max_length=200) sales_this_month = models.DecimalField(blank=True, null=True, max_digits=19, decimal_places=0) saleslm = models.DecimalField(blank=True, null=True, max_digits=19, decimal_places=0) sales2m = models.DecimalField(blank=True, null=True, max_digits=19, decimal_places=0) sales3m = models.DecimalField(blank=True, null=True, max_digits=19, decimal_places=0) def __str__(self): return self.item_n here is my views.py file, that as an experiment I have created, using the last solution provided: def charts(request): charts = Itemslist.objects \ .values('saleslm') \ .annotate(lm=Count('saleslm')) \ .annotate(m2=Count('sales2m')) \ .annotate(3m3=Count('sales3m')) \ .order_by('saleslm') return render(request, 'charts.html', {'charts': charts}) As you can see, this is not a solution I need, I was just trying to come up with at least something , and eaven that has shown me the graph with the same values. here is my hmtl code: {% extends 'base.html' %} {% block js %} {% if user.is_authenticated %} {% load loads_extra %} {% load static %} <br> <p>Logged … -
Can i get a list of models which has foreign key relation with a given model?
I have a model. I want list of models which have foreign key(or any) relation with given model. please help. -
django order_by using a conditional
I need to order my site based on if a field is not null. There are two fields that refer to a deadline, the main full deadline field which is a required field, and a trials field which is optional. All entries will use deadline eventually, but some will have a trials date in there and that will be the one that needs to take priority untill that date is past when it should then default to the deadline. To try to cover just the basics or using one or the other, without it changing when the trials date is passed, I tried the following: class Project(models.Model): ''' Main Project, serves the default Projects Portal window. ''' published = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) area = models.ForeignKey( Area, related_name="project", on_delete=models.PROTECT ) title = models.CharField(max_length=128, unique=True) slug = models.SlugField(max_length=64) summary = models.CharField(max_length=256) others = models.CharField(max_length=128, blank=True) staff_trials = models.DateField(null=True, blank=True) deadline = models.DateField() slip = models.BooleanField(default=False) class Meta: if staff_trials: ordering = ["-slip", "staff_trials"] else: ordering = ["-slip", "deadline"] def __str__(self): return self.title It was a bit of a stab in the dark to hope it would work, but it doesn't surprise me that it didn't work, it appears to … -
What field must be used to store oauth_consumer_key in the Django models?
I am trying to make a django-application that provides a view after authentication using oauth1. The external application sends POST form data with a oauth_consumer_key and I want to validate it with my django application and provide the corresponding view after authentication. Can somebody tell me the flow of this process. I am relatively new to all of this. Also, there is no token exchange in this process. This is the home view for my application from django.shortcuts import render from django.http import HttpResponse from django.template import loader from . import models from django.views.decorators.csrf import csrf_exempt from urllib.parse import urlparse import oauth2 @csrf_exempt def home(request): consumer = None body_dict = dict([(key,value) for key,value in request.POST.items()]) oauth_request = oauth2.Request.from_request(request.method ,body_dict.get('launch_presentation_return_url'),parameters=body_dict) request_key = oauth_request.get_parameter('oauth_consumer_key') if request_key == models.Verify.consumer_key : consumer = oauth2.Consumer(key=request_key,secret = "") signature_method = oauth2.SignatureMethod_HMAC_SHA1() oauth_request.sign_request(signature_method,consumer,None) server = oauth2.Server() server.add_signature_method(oauth2.SignatureMethod_HMAC_SHA1()) try : server.verify_request(oauth_request,consumer, None) except oauth2.Error as e : if str(e)[:18] == 'Expired Timestamp': res = HttpResponse('Unauthorized') res.status_code = 401 return res elif str(e)[:17] == 'Invalid Signature': res = HttpResponse('Unauthorized') res.status_code = 401 return res else: raise e base_template = 'DemoApp/base.html' template = loader.get_template(base_template) return HttpResponse(template.render()) Also I am sure there are a lot more errors in this code. Guide … -
How can I make a product carousel/slider using Bootstrap 4 and Django
I am trying to build a product display slider in Django and finding it thus far impossible. I have successfully built sliders and carousels in static sites before but for some reason attempting to do this with dynamic information using Django is very difficult. I am hoping to create a slider, composed of Bootstrap cards, with a top image, title and price for some products as part of a side project I am doing to practise learning Django and web development. The aim is to display three cards per slide (so three separate products), with a maximum of 5 slides, so no more than 15 products in total for the entire carousel. The title of the carousel will be 'Latest Products', and each time I add a product object to the database the 'first' card will show that object, and the last card (or oldest product) will be pushed off of the end of the carousel so that we don't go over the maximum of 15 cards within the entire carousel. This carousel will be displayed on the home page. So far the view I have for the home page is this: class LatestProductsView(ListView): model = Product.objects.all() template_name = 'products/home.html' … -
Autofill Edit form using Ajax Jquery calls
I have several cards in the UI and each card contains certain data and also has an edit button where the data should get auto-populated(form data) and the user can edit and update it. How do I send the existing data to get it auto-populated through AJAX jquery calls when a user clicks the edit button in the UI? -
How can I generate the GraphQL SDL from the implementation with graphene-django?
I'm using graphene-django to implement a GraphQL API in a Django project. With python manage.py graphql_schema I can dump the Graphene schema (introspection) JSON to a file. Is it possible to do the same for the Graphene schema in schema definition language (SDL (the schema in human readable SDL) representation? -
Fixing the error: django.db.utils.OperationalError: no such table: auth_group
I'm trying to run some simple tests with command: python manage.py test When I do it, I get the error saying File "/Users/petka/.local/share/virtualenvs/movie_platform-wu_Kht1X/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 394, in execute return Database.Cursor.execute(self, query) django.db.utils.OperationalError: no such table: auth_group Anyone knows how to fix this? movies_app/tests.py from django.test import TestCase class SmokeTest(TestCase): def test_bad_maths(self): self.assertEqual(1 + 1, 3) -
Django update HTML table with AJAX
Ok, I tried to understand all the posts here, but I couldn't. Some are outdated, some are not similar to my problem. Don't mind me for asking again. I have a simple(for this test only) HTML table, with some data in it, and I just need to update the data, when it's changed, without refreshing it. But, instead, when I put my main page into ajax URL, I get some duplicates, like, table header gets duplicated. And when I put my get_more_table HTML into ajax URLs, I just get raw JSON data rendered on a page. When I update an object from admin panel, it changes(that's good), but as I said, h1 tag duplicates itself, for some reason. duplicates by itself. My models.py : from django.db import models class CrudUser(models.Model): name = models.CharField(max_length=30, blank=True) address = models.CharField(max_length=100, blank=True) age = models.IntegerField(blank=True, null=True) views.py : from django.http import JsonResponse from django.shortcuts import render from .models import CrudUser def displayUser(request): users = CrudUser.objects.all() context = { 'users': users } return render(request, 'crud.html', context) def updateTable(request): qs = CrudUser.objects.all().values() return JsonResponse({'users': list(qs)}) urls.py : from django.urls import path from crud_ajax import views urlpatterns = [ path('crud/', views.displayUser, name='crud'), path('crud/update_table', views.updateTable, name='update_table'), crud.html, where … -
See supervisor executions in console rather than a logfile
Right now when i do sudo supervisorctl restart all all programs restart.Then whatever has been executed by program tracker_asgi_workers is written into worker.log file. I want to see executions in command line prompt in real time like we see when we do python manage.py runserver. What value should i assign to stdout_logfile variable ? [program:tracker_asgi_workers] command=/home/datasleek/trackervenv/bin/python /home/datasleek/tracker/manage.py runworker stdout_logfile = /home/datasleek/tracker/logs/worker.log process_name=asgi_worker%(process_num)s numprocs=8 environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 ; Set UTF-8 as default encoding autostart=true autorestart=true redirect_stderr=True stopasgroup=true -
Error requesting backend interface using Axios in Vue
In mounted, the requested data can be returned normally when the page is loaded mounted() { axios.get('http://127.0.0.1:8000/api/', {params: {'s': 's'}}) .then((response) => { console.log(response.data); this.items = response.data }); } In methods, data can not be adjusted, and the back end will report errors methods: { search: function() { axios.get('http://127.0.0.1:8000/api/', {params: {'s': 's'}}) .then((response) => { console.log(response.data); this.items = response.data }); } } The error is as follows: enter image description here -
How to retrieve entries from a many-to-many relationship
I have a application, that is used to manage assistant jobs. Therefore, the model is composed of 3 models: Person, Course, Application (typical many-to-many relation). My models.py looks as follow: class Person(AbstractUser): ... class Course(models.Model): year = models.charField(max_length=9) term = ... class Applications(models.Model): applicant = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="applicant") course = models.ForeignKey(Course, on_delete=models.CASCADE) status = models.CharField(max_length=255, default='Pending') In the context of a form, I need to retrieve all the courses a person has been hired in order to populate a dropdown list. It is easy to get all the applications of the currently logged in user having the status 'Hired': Applications.objects.filter(applicant=user, status="Hired") but I can't get a a queryset of all the related courses: Applications.objects.filter(applicant=user, status="Hired").course_set returns me an: AttributeError: 'QuerySet' object has no attribute 'course_set' As per Django documentation, this attribute should exist. What am I doing wrong? -
My JavaScript variable not able to accept object which I have send using Django render() method
I was trying to fetch Django object in JSON format to my javascript variable. I have used from django.core import serializers predefined method available in Django, to convert it into JSON format. When I was trying to fetch that object directly into Jinja tag then it prints all the data, but when I was trying to get that data in Javascript variable then it won't work. view.py from django.http import HttpResponse from django.shortcuts import render from .models import Employee from django.core import serializers import json def home(request): data = serializers.serialize("json", Employee.objects.all()) return render(request,'home.html',{'data':data}) home.html <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> {% extends 'masterpage.html' %} {% block content %} **{{data | safe}}**(go below for output) <form action="checkEmail" method="POST"> {% csrf_token %} <input type="text" name="emailId" placeholder="Enter Email Id"> <input type="submit"> </form> {% endblock %} <p id="demo"></p> <script type="text/javascript"> var data=eval('('+'{{data}}'+')'); var p=10; document.getElementById("demo").innerHTML=p console.log(p) console.log(data); alert(data); </script> </body> </html> Output : [{"model": "journal.employee", "pk": 1, "fields": {"ename": "Piyush Jiwnae", "eemail": "jiwanepiyush@gmail.com"}}] I can see the output for direct use of jinja tag in HTML but when I try to get that value in javascript variable it won't come … -
how to return a django view from within a celery task?
I need to return a form from inside a django celery task. My task is called from the following django view: class MyView(CreateView): model = MyModel form_class = MyForm success_url = '/create/form' def form_valid(self, form): form.save() # I call my task in here period.delay() print("Loading task...") return super(MyView, self).form_valid(form) The name of my task is "period" and It compares dates with the objective to open a event while the condition in my IF is true. My "event" is a formulary that user has to confirm presence. My task: from .views import MyAnotherView # others imports... """ in my settings.py, I had to call tha task every minute: CELERYBEAT_SCHEDULE = { 'add-periodic-events': { 'task': 'myapp.tasks.period', 'schedule': crontab(minute='*'), } } """ @shared_task(serializer='json') def period(): event = MyModel.objects.get(id=1) # I limited my model to receive only one object request = RequestFactory.get('/another/form') view = MyAnotherView() week_d = week_day(event.day) # day is a field of my model event_d = event_day(week_d, event.hour) # hour is a field of my model conf_d = presence_confirm(event.before_days, event.begin_hour, event_d) # before_days and begin_hour are fields of my model utc_now = pytz.utc.localize(datetime.utcnow()) n = utc_now.astimezone(pytz.timezone('America/Recife')) t_str = '{}-{}-{}'.format(n.year, n.month, n.day) t_hour = ' {}:{}'.format(n.hour, n.minute) today = t_str + t_hour today … -
heroku logs --tail shows ModuleNotFoundError: No module named 'user'
i have created a project with django and heroku postgresql and deployed the project to heroku with heroku CLI. Procfile web: gunicorn hoj.wsgi --log-file - heroku logs --tail shows import error like in image here1 in left we can see project directory. i dont know why its an import error! is there any problem in project directory? -
Django foreign keys concept not implemented [closed]
Why am I unable to use the concept of foreign keys in Django? Actually i was going through the Django documentation and doing all the steps as were listed in it but when i have runned the command to make migrations for polls app then -Add field question to choice was missing from the result of the command https://docs.djangoproject.com/en/3.0/intro/tutorial02/ under activating models section command python manage.py makemigrations poll -
Django speeding up slow Subquery
I'm trying to annotate each Customer with Boolean value - if any related CustomerTemplate objects exist that have a Product where the sum of indicator_1 and indicator_2 is not zero. Basically this will indicate that the product's price has changed. To accomplish this I'm using the Subquery below but it is quite slow. Is there any way to speed up this query? class Product(models.Model): indicator_1 = models.IntegerField() indicator_2 = models.IntegerField() class Customer(models.Model): templates = models.ManyToManyField( Product, blank=True, through='CustomerTemplate', through_fields=('customer', 'product'), ) class CustomerTemplate(models.Model): customer = models.ForeignKey(Customer, ...) product = models.ForeignKey(Product, ...) Adding db_index=True to the indicator fields on the product model does provide any increases. All foreign keys are already indexed. Customer.objects.annotate( has_price_change=Subquery( CustomerTemplate.objects .filter(customer=OuterRef('pk')) .values('customer') .annotate( price_change=Coalesce( Sum(Func(F('product__indicator_1'), function='ABS')) + Sum(Func(F('product__indicator_2'), function='ABS')), 0) ) .annotate( has_price_change=Case( When(price_change__gte=1, then=True), default=False, output_field=BooleanField() ) ) .values('has_price_change') ) ) I've tried using Exists but for some reason it doesn't work at all - the response times out. Customer.objects.annotate( has_price_change=Exists( CustomerTemplate.objects .annotate( price_change=Coalesce( Sum(Func(F('product__indicator_1'), function='ABS')) + Sum(Func(F('product__indicator_2'), function='ABS')), 0 ) ) .filter(customer=OuterRef('pk'), price_change__gte=1) ) )