Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ListView derived classes ignoring paginate_by field
I am using Django 3.2 I am using OOP to keep my code DRY. I have a base class Foo (which derives from ListView), and I am setting common properties in that class. I then have two specialisations of Foo - which I expect to be cognisant of the paginate_by member variable - however, the subclasses seem to be ignoring the variable I set paginate_by to, as it has no effect. This is my code: class UserFooList(LoginRequiredMixin, ListView): http_method_names = ['post'] paginate_by = 2 def post(self, request, *args, **kwargs): # some processing logic return render(request, '/path/to/Foo_list.html', context=context, status=status_code) class UserApprovedFooList(UserFooList): def get_queryset(self): return Foo.objects.prefetch_related().filter(/* query criteria one */) class UserFoosInModerationQueueList(UserFooList): def get_queryset(self): return Foo.objects.prefetch_related().filter(/* query criteria two */) Why is the paginate_by field being ignored by UserApprovedFooList and UserFoosInModerationQueueList - and how do I resolve this? -
{% include %} django template issue
I'm trying to connect my header for a new file, I do it like this {% include filename%}. in other files it works without any problem. Now it only connects the html itself but without statics. {% load static %} <!DOCTYPE html> <html > <head> <meta charset="UTF-8"> <title>Sign In/Up</title> </head> {% include 'inc/_header.html' %} settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'essense/static'), ] -
django.db.utils.OperationalError : This probably means the server terminated abnormally (only Django app)
I am currently trying to connect to a Sage Evolution server from a django web application The below error is displayed when I run "inspectdb" or "inspectdb > models.py" The server does connect when I ping it through the command prompt and connect to it via the .bat file I had created to test the connection. So I don't see why it would be an error on the servers side C:\Users\KylePOG\Documents\GMA Programming\accConnect>python manage.py inspectdb > models.py Traceback (most recent call last): File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\KylePOG\Documents\GMA Programming\accConnect\manage.py", line 22, in <module> main() File "C:\Users\KylePOG\Documents\GMA Programming\accConnect\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) … -
Django RestAPI but without CSS
I am making an REST API using Django Restframework It works perfectly but I get an error when I have pushed it to railway app like this Installing SQLite3 -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/workspace/manage.py", line 22, in <module> main() File "/workspace/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 338, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 248, in delete_file if self.storage.exists(prefixed_path): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/files/storage.py", line 318, in exists return os.path.exists(self.path(name)) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 38, in path raise ImproperlyConfigured("You're using the staticfiles app " django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ERROR: failed … -
{'required': 'This field is required.', 'null': 'This field may not be null.', 'invalid': 'Invalid data. Expected a dictionary, but got {datatype}.'}
This is the error which is thrown by the serializer.is_valid(). I don't know why this error come. I am new to Django Rest Framework. I am trying to make a simple invoice generating api. which takes info about seller, buyer, items and generate a invoice. So I write models for each and one model for invoice in which seller, buyer are foriegn key. Item model is related to invoice model through a foreign key. Any Help is appreciated. This is my models.py class Seller(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) phone = models.CharField(max_length=12) address = models.CharField(max_length=200) def __str__(self): return self.name class Buyer(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) phone = models.CharField(max_length=12) address = models.CharField(max_length=200) def __str__(self): return self.name class Invoice(models.Model): id = models.AutoField(primary_key=True) seller = models.ForeignKey(Seller, on_delete=models.CASCADE) buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) def total_amount(self): total = Decimal('0.00') for item in self.items.all(): total = total + item.total() return total def invoice_number(self): if len(str(self.id))==1: return 'Invoice00'+self.id elif len(str(self.id))==2: return 'Invoice0'+self.id else: return 'Invoice'+self.id def __str__(self): return f'{self.seller} {self.buyer} {self.date}' class Item(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=20) invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE) price = models.DecimalField(decimal_places=2, max_digits=20) quantity = models.IntegerField(default=1) tax = models.DecimalField(decimal_places=2, max_digits=4) def total(self): total = Decimal(str((self.price-self.tax)*self.quantity)) return total.quantize(Decimal('0.01')) def … -
Django FilterSet, Count and Distinct
I'm building a custom filter for a model, and I wanted to have two optional boolean fields that would alter the way the queryset is created. One boolean for distinct, that would make the result be only unique values, like in .distinct(), and another boolean for count, that would instead return the number of items, like with a .count() I have found this: https://django-filter.readthedocs.io/en/stable/ref/filters.html#distinct but i cant really understand how to use it. Also, I haven't found a way for count My filter looks like this: class MyModelFilter(django_filters.FilterSet): class Meta: model = Inventory fields = ( "service", "provider" "recorded_at", "tenant", "tenant_name", "project_system", "area", "environment", "region", ) data_filter = django_filters.CharFilter(method="json_filter") def json_filter(self, queryset, name, value): string_to_json = json.loads(value) return queryset.filter(data__contains=string_to_json) -
Access a Django server from a VM Linux deployed with Amazon EC2
I have developed a Django app on a Amazon EC2 virtual machine which I access using ssh. When I run python manage.py runserver, everything works fine, and I have Django version 3.2.6, using settings 'crm.settings' Starting ASGI/Channels version 3.0.4 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. The thing is I would like to see the result of this app in a browser, either on the VM or in the browser of my computer (of course 127.0.0.1 is not working on my "main" Linux) So far, I have tried ipconfig in the VM, but I do not know what to do with the output. Do you guys have any idea / clue? Any assistance is appreciated, feel free to ask for specifications. Thanks in advance -
setting conditional serializer class removes the custom serializer class for extra action in Django rest framework
I have one modelviewset and couple of extra actions for it. class TestViewset( mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.UpdateModelMixin, GenericViewSet, ): permission_classes = [CustomPermissionClass] def get_serializer_class(self) -> Type[ModelSerializer]: if self.action == "list" or self.action == "get": return FirstSerializer return SecondSerializer @action( detail=True, methods=["POST"], url_path="test-path", url_name="test-path", serializer_class=MyCustomSerializer, ) def test_path(self, request: Request, **kwargs) -> Response: print(self.get_serializer()) # Despite setting the 'MyCustomSerializer' it still gives me 'SecondSerializer' return Response(status=status.HTTP_200_OK) If I remove the get_serializer_class method and give only one serializer it works. What could be the best solution for this or is this any bug in drf? Ideally the extra action should use the serializer class that has been provided but its not. -
Compare and groupby using Django ORM
I have 8 objects from 2 different models. Say, Fruit and Colour I want to filter and group Fruits based on Benefits. For instance, Orange and Grapes can be grouped together because they share similar benefits , i.e. "rich in vitamin C" Here's my code: models.py class Fruit(models.Model): name = models.CharField(max_length=40, blank=True, null=True) colour = models.CharField(max_length=40, blank=True, null=True) benefits = models.JSONField(default=dict) class Benefit(models.Model): health_benefit = models.CharField(max_length=240, blank=True, null=True) I tried the following: all_benefits = Benefit.objects.values_list('health_benefit') Fruit.objects.filter(benefits__in=all_benefits) Not sure if this is the correct way to query. Thanks in advance. -
How to pass non string to innerHTML
I am using django, basically i am trying to change some part of the html code using javascript. below chart work nicely <div id='treemap_charts'> {{ treemap_code.first.treemap_price_difference_yesterday|safe }} </div> with final result being <div id='treemap_charts'> HTML code </div> However, when I added some javascript to alter the content inside the div id='treemap_charts' as shown below: <script> document.addEventListener('DOMContentLoaded', function(){ document.querySelector("#treemap_options").onchange = function() { if (this.value==='day') { document.querySelector('#treemap_charts').innerHTML='{{treemap_code.first.treemap_price_difference_yesterday}}'; } else { document.querySelector('#treemap_charts').innerHTML='{{treemap_code.first.treemap_price_difference_month}}'; } } }); </script> <div> <select id='treemap_options' name='Treemap Charts'> <option value='day' selected>1 Day Performance</option> <option value='week'>1 Week Performance</option> </select> </div> <div id='treemap_charts'> {{ treemap_code.first.treemap_price_difference_yesterday|safe }} </div> the HTML result end up as a string instead of HTML code <div id='treemap_charts'> "HTML code" </div> PS:I try to use this code but it does not work <script> document.addEventListener('DOMContentLoaded', function(){ document.querySelector("#treemap_options").onchange = function() { if (this.value==='day') { document.querySelector('#treemap_charts').innerHTML='{{treemap_code.first.treemap_price_difference_yesterday|safe}}'; } else { document.querySelector('#treemap_charts').innerHTML='{{treemap_code.first.treemap_price_difference_month|safe}}'; } } }); </script> Anyidea how I can pass {{ treemap_code.first.treemap_price_difference_yesterday|safe }} to the div without it changing to string? I search around the forum but seem unable to get the answer but one thing I learn is at least in the HTML need to have |safe else it will not work... -
Editing foreign keys in django-forms
I recently got into django and django forms. What i'm trying to do is make a form where my foreign key is editable. (a form of the other model where my foreign key is refering to inside a form). so lets say I have these models class Model2(models.Model): name = models.CharField(max_length=50) class Model1(models.Model): type = models.ForeignKey(Model2, on_delete=models.CASCADE) value = models.CharField(max_length=50) # other fields When you render the form for Model1, the foreign key must be editble aswell. I'm wondering if anything like this is possible -
Is there way to gracefully remove a Django plugin from the project
We have installed a charting plugin in our Django project, but we found another one that more suits our requirements. Is there a way to gracefully remove the plugin from our project? -
Django how to force page reload on event
I am developing an application that communicates with measurement system. Clicking "start test" button causes redirection to the "test_in_progress" view which is just a sign "test in progress" with progress spinner. In that view the application awaits response from the measurement system. I want to redirect to the "test_results" view when the message comes and I don't really know how to do that. Should I just set some flag and in "test_in_progress" page poll for the flag periodically with js (if this is the right approach then how to do that?). Or is there any way to force page redirection from within python? -
using Hebrew language in django and xhtml2pdf to save pdf
Hi I can't figure this up but how do I save pdf with Hebrew charcters in xhtml2pdf I can't find anything online the code suppose to acceses a property from the database and then create a pdf file and sent it to the client mail pyhon code that convert template to pdf from django.template.loader import get_template from os.path import join from .utils import render_to_pdf from django.http import HttpResponse from xhtml2pdf import pisa def generate_pdf(property): template = get_template("main/pdftabo.html") context = { "address": f'{property.street} {property.building_number} {property.city}', "owners": property.owners, "loan": property.loan, "plot": property.plot, } html = template.render(context) filepath = join('static',f'media/{property.block}{property.lot}.pdf') write_to_file = open(filepath, "w+b") result = pisa.CreatePDF(html,dest=write_to_file) write_to_file.close() the pdf template html code <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> {% load static %} <html lang="heb"> <head> <meta charset="character_set"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> @font-face { font-family: MyRightToLeftFont; src: url("{% static 'fonts/ahronbd.ttf' %}") } p { font-family: MyRightToLeftFont } </style> </head> <body> <pdf:language name="hebrew" /> <p>שלום</p> <table> <tr> <th>מגרש</th> <th>מס' בית</th> <th>מס' הדירה לפי הסכם המכר</th> <th>מהוות הנכס</th> </tr> <tr> <th>{{plot}}</th> <th>7</th> <th>1</th> <th>{{address}}</th> </tr> </table> </body> </html> image of what i get -
How to embed a Django application on a Wix website?
How do I embed a Django application inside a Wix website? I have my app hosted on a server, but now I want to embed this app inside a Wix website. I've made a couple of changes to the settings.py such as Commenting out csrf middleware and Xframeoptions middleware. Added these lines SESSION_COOKIE_SAMESITE = 'None' # As a string SESSION_COOKIE_SECURE = True X_FRAME_OPTIONS = 'ALLOWALL' XS_SHARING_ALLOWED_METHODS = ['POST','GET','OPTIONS', 'PUT', 'DELETE'] Added @csrf_exempt on top of every function in my views.py file. Although it's rendering the website, the only function that does not work is the sign in and register option, and that too only in the Wix website, it works fine when I sign in or register through the actual server domain but not when I do it through Wix. I'm not sure if it has something to do with Wix itself or Django, so can someone help my figure this issue out if it is even possible in the first place? -
Changing the default user while using REST framework JWT
I have a proxied user model: class TheDude(User): class Meta: proxy = True And I'm using the Django REST framework JWT to do JWT auth in the REST API. I'd like to get the user object from the request but currently it's a User object. Because it's proxied I can't use AUTH_USER_MODEL. I've tried doing a middleware component to override the user in the request but it's not set at that stage. I've also tried using JWT_RESPONSE_PAYLOAD_HANDLER however my function isn't called so I can't set it there either. If I want to be able to get TheDude object when I call request.user instead of User in my views, how would I do this while authing using the REST framework JWT Auth library? -
Django, How to update DateTimeField attribute only when one specific attribute is changed
I would like to update the attribute date_assigned only when the attribute Customer is changed. I know that I have to overwrite the save function within the same model but i don't know exactly how. class Ip(models.Model): customer = models.ForeignKey(Customer, null=False, on_delete=models.CASCADE) ip = models.GenericIPAddressField(protocol="IPv4", null=False, unique=True) date_created = models.DateTimeField(auto_now_add=True,) date_updated = models.DateTimeField(auto_now=True,) date_assigned = models.DateTimeField(auto_now=True) Any ideas? thanks in advance. -
Unable to publish data from inherited class - paho django
Initialized paho mqtt as a class class Initializer(): def __init__(self): self.client = mqtt.Client(mqtt_server+str(int(time.time()))) self.client.username_pw_set( username=mqtt_username, password=mqtt_password) self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_subscribe = self.on_subscribe self.client.connect(broker, mqtt_port) self.client.loop_start() def on_connect(self, client, userdata, flags, rc): if rc == 0: #app_logger.info("Device Connection Established") print("Device Connection Established") else: #app_logger.info("Bad Connection") print("Bad Connection") then i have created a another class that inherits initializer class class send(Initializer): def __init__(self): super().__init__() self.client.publish("topic","data") able to print the value of self.client inside the initialization of send class but not able to publish data. -
Does form_valid() in CBV not call is_valid() method?
When I used function views, It was able to handle cleaned_data with overriding form.clean() method. I thought when I call form.is_valid method, form.clean() is called too. Form validation happens when the data is cleaned. If you want to customize this process, there are various places to make changes, each one serving a different purpose. Three types of cleaning methods are run during form processing. These are normally executed when you call the is_valid() method on a form. Now I'm trying to do same things with class-based-view, but it does not work as I thought. Here's my forms.py: class PublishForm(forms.ModelForm): class Meta: model = models.Article exclude = [ 'author', ] def __init__(self, user, *args, **kwargs) -> None: self.user = user return super(PublishForm, self).__init__(*args, **kwargs) def is_valid(self): print('IS_VALID METHOD CALLED') return super(PublishForm, self).is_valid() def clean(self): print('CLEAN METHOD CALLED') cleaned = super(PublishForm, self).clean() cleaned['author'] = self.user return cleaned and views.py: class PublishView(generic.CreateView): form_class = forms.PublishForm success_url = '/' template_name = 'ex00/publish.html' def form_valid(self, form): print(form.cleaned_data) return super(PublishView, self).form_valid(form) def form_invalid(self, form): print(form.errors) return super(PublishView, self).form_invalid(form) It seems form_valid() does not call neither form.is_valid() or form.clean(). But It was able to get form.cleaned_data(). How does form_valid() work? What should I do to manipulate cleaned_data … -
Django: traceback appears on form as text after Bad Request 400
I have ajax views for editing and saving objects. When I am editing an object, the appropriate forms and formsets are loaded with instantiated data. Now I am getting this error when a user tries to add more than 1000 fields: POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. The problem is that the traceback code is inserted directly on the form and becomes visible to all: By design, I am expecting a response code on frontend, which is 400 for django form errors. However, in this case, the 400 error comes from the bad request, and not from form errors. As a result, after saving the object, I have the full traceback displayed right in the form as plain text. How can I avoid this behaviour? I want not to display the traceback/bad request error text on the form to the users. My only idea is to change the default status code of django form errors to some 444 and to display only the 444 errors on forms, while ignoring the 400 errors traceback. But I don't know how to do it and don't think this is the best option either. -
The default django `User` model generating huge number of queries, when working with views in DRF?
I am trying to build an endpoint for the default User model, which we have in django, which being imported from from django.contrib.auth.models import User, This is my serializer:- class SuperUserDetailSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( 'id', 'username', 'groups', 'user_permissions', 'organization_users', ) and the views goes as this:- class UserDetailView(RetrieveUpdateDestroyAPIView): queryset = User.objects.all() serializer_class = SuperUserDetailSerializer with the above codes, the number of queries which being hit are 216-219, which is due to the field user_permissions, I checked the User model, but it doesn't contains any field as user_permissions, but in the response, I get this field, and also in the html form field the permissions are populated(DRF Browsable page). I am trying to implement prefetch_related or select_related for the user_permissions field, but I am not able to reduce the the number of query, (It is hitting the database each time for getting all the permissions). This is what I am trying to do but not able to achieve it:- queryset = User.objects.prefetch_related(Prefetch('user_permissions', queryset = Permission.obects.select_related('content_type')))...I am not sure where I am doing the mistake. -
Django Rest Best practice of handling complex data composition
I am a bit of a django newbiew so forgive me if I miss somehow something obvious. I have a database table representing a linguistinc term called terms. This term can be included in several string attributes of not directly related tables such as say article. Now I have a direct requirment to return those items when aksed for the details of a term. An example schema could look like the following { 'name': 'Some term definiton', 'another_attribute': 'some attribute value', 'articles': ['Articles that include text'] } Not the most efficient way but in order to find the 'associated' articles I have method called find_associated_articles which in essense performs a full text search on the articles text to find potential matches of particular term. No the question is what would be the most Django way of compositing this information in a Rest Response (Idealy in the context of a retrieve action within a viewset)? -
How to upload and process large excel files using Celery in Django?
I am trying to upload and process excel file using Django and DRF with Celery. There is an issue when I am trying to pass the file to my Celery task to be processed in the background, I get a following error: kombu.exceptions.EncodeError: Object of type InMemoryUploadedFile is not JSON serializable Here is my view post request handler: class FileUploadView(generics.CreateAPIView): """ POST: upload file to save data in the database """ parser_classes = [MultiPartParser] serializer_class = FileSerializerXLSX def post(self, request, format=None): """ Allows to upload file and lets it be handled by pandas """ serialized = FileSerializerXLSX(data=request.data) if serialized.is_valid(): file_obj = request.data['file'] # file_bytes = file_obj.read() print(file_obj) import_excel_task.delay(file_obj) print("its working") return Response(status=204) return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) And my celery task: def import_excel_helper(file_obj): df = extract_excel_to_dataframe(file_obj) transform_df_to_clientmodel(df) transform_df_to_productmodel(df) transform_df_to_salesmodel(df) @shared_task(name="import_excel_task") def import_excel_task(file_obj): """Save excel file in the background""" logger.info("Importing excel file") import_excel_helper(file_obj) Any idea what is the way to handle importing Excel files into celery task so that it can be processed by other functions in the background? -
Mapbox add marker on click
I am building a website in django, and im using Mapbox as a way to add markers on a map. Right now my solution is a django form, with fields for 'longitude', 'latitude', 'Marker_Title'. A solution would be to either add the longitude and latitude to the form by clicking on the map, or clicking on the map and then a popup appears where you can write the marker title. I am not sure how i get the longitude and latitude information by clicking right now. Here is a picture of how it looks right now: Picture of the map and form I would love if anyone can help me with this! Thanks in advance! -
Compare data from a week(or minute) ago using a queryset in Django
I have some data as follows: class myModel(models.Model): date = models.DateTimeField user_ID = models.CharField index_a = models.CharField cnt_a = models.BigIntegerField cnt_b = models.BigIntegerField I would like to get Result data as follows: date user_ID sum(n.a) sum(-5min) sum(n.b) sum(-5min) 2021-08-01 13:00 a10 7011 6625 9239 8766 2021-08-01 13:00 a20 6968 6628 9238 8765 2021-08-01 13:00 a30 6940 6646 9238 8766 2021-08-01 13:00 a40 6974 6644 9238 8764 2021-08-01 12:55 a10 6625 6621 8766 8692 2021-08-01 12:55 a20 6628 6580 8765 8691 2021-08-01 12:55 a30 6646 6596 8766 8693 2021-08-01 12:55 a40 6644 6614 8764 8692 I tried SQL query as follows: and get the Result as above Table I am trying to use queryset in Django to perform the following query without using raw SQL. any idea how can do that? Thanks in advance! SELECT n.date, n.user_ID, sum(n.cnt_a), sum(p.C_AAA), sum(n.cnt_a), sum(p.C_BBB) FROM myModel AS n LEFT JOIN ( SELECT t1.date, t1.user_ID, t1.index_a, t1.cnt_a as C_AAA , t1.cnt_b as C_BBB FROM myModel AS t1 ) AS p ON p.date = DATE_SUB(n.date, INTERVAL 5 MINUTE) AND p.user_ID = n.user_ID AND p.index_a = n.index_b