Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SystemError: PY_SSIZE_T_CLEAN macro must be defined for '#' formats in django project
I am trying to run the code.But none of the below commands working: python manage.py runserver. pyhton manage.py makemigrations pyhton manage.py showmigrations I am getting below error: I am doing this in ubuntu Traceback (most recent call last): File "/home/zapbuild/ZapbuildProjects/timetracker/timetracker/manage.py", line 21, in <module> main() File "/home/zapbuild/ZapbuildProjects/timetracker/timetracker/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/backends/base/base.py", line 197, in connect self.init_connection_state() File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 231, in init_connection_state if self.features.is_sql_auto_is_null_enabled: File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/backends/mysql/features.py", line 82, in is_sql_auto_is_null_enabled cursor.execute('SELECT @@SQL_AUTO_IS_NULL') File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/MySQLdb/cursors.py", line 312, in _query db.query(q) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/MySQLdb/connections.py", line 224, in query … -
there are "room" is not accessedPylance
It was my views.py codes It was my urls.py codes How i can solve this error. -
Does anyone know where Elastic Beanstalk stores my Django models?
I am creating an app in Django, and I am hosting it on Elastic Beanstalk. I want to know where it stores my models, because I don't know whether Django isn't saving models when I save them from a ModelForm, or if Elastic Beanstalk stores the models somewhere else. This is kind of like an extension to my other problem: 'form.save(commit=True)' not saving to database -
How to send context request in DRF Management Commands without request Object
I stuck now 2 days on this, for cache reasons I store data in memcache - Im collecting data with managemend-commands from django - if I collect data all the urls are relative - for absolute path i need to pass context to serializer - but I dont have this. How can I solve this problem to get the full path? Any Idea? For the public view it works well - but if I develop with localhost then i have troubles with the urls. I tryed fake a request object with requestfactory or testclient but not worked :D -
Wrong value for variable is being given
so I have a problem with some variables, which are coming from an dictionary iteration: for rank in ranked_stats: if rank['queueType'] == "RANKED_FLEX_SR": flex_rank_name = "Ranked Flex" flex_tier = rank["tier"] flex_rank = rank['rank'] totalrank_flex = flex_tier + " " + flex_rank winrate_flex = rank['wins']/(rank['wins']+rank['losses']) winrate_flex *= 100 winrate_flex = "{:.2f}%".format(winrate_flex) wins_flex = rank['wins'] losses_flex = rank['losses'] else: flex_rank_name = "None" flex_tier = "None" flex_rank = "None" totalrank_flex = "None" winrate_flex = "None" wins_flex= "None" losses_flex = "None" for ranksolo in ranked_stats: if ranksolo['queueType'] == "RANKED_SOLO_5x5": solo_rank_name = "Ranked Solo/Duo" solo_tier = ranksolo['tier'] solo_rank = ranksolo['rank'] totalrank_solo = solo_tier + " " + solo_rank winrate_solo = ranksolo['wins']/(ranksolo['wins']+ranksolo['losses']) winrate_solo *= 100 winrate_solo = "{:.2f}%".format(winrate_solo) wins_solo = ranksolo['wins'] losses_solo = ranksolo['losses'] else: solo_rank_name = "None" solo_tier = "None" solo_rank = "None" totalrank_solo = "None" winrate_solo = "None" wins_solo= "None" losses_solo = "None" These are the loops for this dictionary: [{"leagueId": "0b36ed94-33bc-43e3-aa39-3bff2350f76e", "queueType": "RANKED_SOLO_5x5", "tier": "BRONZE", "rank": "II", "summonerId": "___hidden__", "summonerName": "lantern is lava", "leaguePoints": 57, "wins": 8, "losses": 5, "veteran": false, "inactive": false, "freshBlood": false, "hotStreak": false}, {"leagueId": "52002724-73b2-49bc-ad7b-ae58c64f2623", "queueType": "RANKED_FLEX_SR", "tier": "BRONZE", "rank": "II", "summonerId": "__hidden__", "summonerName": "lantern is lava", "leaguePoints": 1, "wins": 5, "losses": 5, "veteran": false, "inactive": false, "freshBlood": false, … -
How to set SSL on another port besides port 80 for react/django/nginx app
Here is my nginx.conf. SSL works on port 80/443, and I can go to the url mynacode.com with https, however I also want to access my backend on port 8000 using secured https connection. How can I do that? Right now, I can access my backend with an insecure connection i.e. http://www.mynacode.com:8000. I would like to use a secured url https://www.mynacode.com:8000 as well. upstream api { server backend:8000; } server { listen 8080; server_name mynacode www.mynacode.com; location /.well-known/acme-challenge/ { root /var/www/certbot; } location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; server_name mynacode www.mynacode.com; ssl_certificate /etc/letsencrypt/live/www.mynacode.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/www.mynacode.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; location / { proxy_read_timeout 300s; proxy_connect_timeout 75s; root /var/www/react; try_files $uri /index.html; proxy_set_header Host $host; } location /api/ { proxy_read_timeout 300s; proxy_connect_timeout 75s; proxy_pass http://api; proxy_set_header Host $http_host; } } I've tried searching answers on stackoverflow but have been unsucessful so far. Any help would be appreciated! -
I started a Django course and in that I am using data grip. I am new to this framework and MySQL
When I uploaded the SQL file into data grip it shows me an error. Please refer to the image that you can see the error I tried changing the SQL code in many ways but it didn't work out. please help me. -
How to align boxes in horizontal using css
Can anybody tell me how to align these boxes in horizontal. I use loop and getting input using rending url as you can see in screenshot. Can anybody tell me how to print them in horizontal, using css i am doing this in flask also rending the url for getting input so color and box numbers change. -
django, sendGrid not sending mail
I'm trying to send mail using SendGrid on django development server. Here are my setting: EMAIL_HOST = 'smtp.sendgrid.net' DEFAULT_FROM_EMAIL = 'myemail@gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_USE_SSL = False EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = config('PASS') and it is not working, it returns 1 on the terminal and nothing happens. -
Django user log in
In django, i cannot log in even as a superuser on the site but only at the django admin page. same as users created through the site cannot log in after they succesfully signed up. once they log out after signing up, they are not able to log in again. I am expecting all users that signed up to be able to log in even after they log out -
django crispy form does not work in the template
I'm trying to make my form-fields to be in a row like this html code down below, but it does not work, I want all the fields in the PrimryForm class to be in a row not in a column: Html code: <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <div class="container"> <div class="row"> <div class="col"> <div class="form-group"> <input type="text" class="form-control"> </div> </div> <div class="col"> <div class="form-group"> <input type="text" class="form-control"> </div> </div> <div class="col"> <div class="form-group"> <input type="text" class="form-control"> </div> </div> </div> </div> Forms.py file: from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Row, Column class PrimaryForms(forms.ModelForm): signature_of_student = JSignatureField( widget=JSignatureWidget( jsignature_attrs={'color':'#e0b642', 'height':'200px'} ) ) signature_of_guardian = JSignatureField( widget=JSignatureWidget( jsignature_attrs={'color':'#e0b642', 'height':'200px'} ) ) date_of_birth = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) class Meta: model = Primary fields = ['admission_number', 'profile_picture', 'first_name', 'last_name', 'gender', 'address_of_student', 'class_Of_student', 'comment_of_student', 'year_of_graduation', 'date_of_birth', 'religion', 'mother_name', 'signature_of_student', 'relationship', 'signature_of_guardian'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-3' self.helper.field_class = 'col-md-9' My Form/template: {% load crispy_forms_tags %} <div class="container"> <div class="row justify-content-center"> <div class="col"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% crispy form %} <br> <button type="submit" class="btn btn-primary">Create Student</button> </form> </div> </div> </div> How can I do this using django-crispy-form? -
Django CKEditor RichTextEditorWidget Admin not working
I'm trying to create a textfield with CKEditor >>> from ckeditor.widgets import CKEditorWidget to be able to add notes for every row in the admin and save them. I followed the tutorial on CKeditor docs and its not working. There are no error its just the CKEditorWidget not showing in the textfields. here is my admin.py file: from django import forms from django.contrib import admin from ckeditor.widgets import CKEditorWidget # Register your models here. from .models import Inventory from import_export.admin import ImportExportModelAdmin class InventoryAdminForm(forms.ModelForm): notes = forms.CharField(widget=CKEditorWidget()) class Meta: model = Inventory fields = '__all__' class InventoryAdmin(ImportExportModelAdmin): list_display = ['sku','qty','price','notes'] list_filter = ('sku','qty','price',) search_fields = ('sku','qty','price',) list_editable = ('qty','price','notes') list_max_show_all = True form = InventoryAdminForm admin.site.register(Inventory, InventoryAdmin) the text editor is not showing up. -
Type checking error: views.py:24: error: "HttpRequest" has no attribute "tenant"
I am creating a Django application which is multi-tenanted. The custom middleware I use attaches a tenant object to the request. My issue is when type checking, my views are not aware of extra attribute on the HttpRequest class. I have tried creating a TenantHttpClass which extends HttpRequest and adds the tenant attribute. How do I make my views aware of this. My code is below: middleware/main.py: from typing import Type from django.db import connection from django.http import Http404 from django.utils.deprecation import MiddlewareMixin from apps.tenants.custom_request import TenantHttpRequest as HttpRequest from apps.tenants.models import Domain, Tenant from apps.tenants.utils import get_public_schema_name, get_tenant_domain_model, remove_www from vastdesk import settings class TenantMainMiddleware(MiddlewareMixin): TENANT_NOT_FOUND_EXCEPTION: Type[Http404] = Http404 """ This middleware should be placed at the very top of the middleware stack. Selects the proper database schema using the request host. Can fail in various ways which is better than corrupting or revealing data. """ @staticmethod def hostname_from_request(request: HttpRequest) -> str: """Extracts hostname from request. Used for custom requests filtering. By default removes the request's port and common prefixes. """ return remove_www(request.get_host().split(":")[0]) def get_tenant(self, domain_model: Domain, hostname: str) -> Tenant: domain = domain_model.objects.select_related("tenant").get(domain=hostname) return domain.tenant def process_request(self, request: HttpRequest) -> None: # Connection needs first to be at … -
mail is not sent in django help no se envia mail en django
I try to get an email from my page that I made in django, but it doesn't, I did if it was sent, tell me that it was sent correctly, and if it was not sent, it would redirect me to the same page. The problem is that it is never sent correctly, as if something was wrong directly when I coded the view or something like that. the problem is that it is never sent. the POST is never sent. Views.py from django.shortcuts import render , redirect from .forms import FormularioContacto from django.core.mail import EmailMessage # Create your views here. def contacto(request): formulario_contacto=FormularioContacto() if request.method == "POST": formulario_contacto=FormularioContacto(data=request.POST) if formulario_contacto.is_valid(): nombre= request.POST.get("nombre") email= request.POST.get("email") numero= request.POST.get("numero") contenido= request.POST.get("contenido") email=EmailMessage("mensaje desde app django", "el usuario con el nombre: {} con la direccion: {} y el numero: {} te escribe: \n\n {}".format(nombre, email, numero, contenido), "", ["faustofernandezes@gmail.com"], reply_to=[email]) try: email.send() return redirect("/contacto/?valido") except: return redirect("/contacto/?novalido") return render(request, "contacto/contacto.html" , {'miFormulario' : formulario_contacto}) settings: STATIC_URL = '/static/' MEDIA_URL='/media/' MEDIA_ROOT=BASE_DIR / 'media' # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' #config de mail EMAIL_BACKEND="django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST="smtp.gmail.com" EMAIL_USE_TSL=True EMAIL_PORT=587 EMAIL_HOST_USER="faustofernandezes@gmail.com" EMAIL_HOST_PASSWORD="Here I put my 2-step verification application password" html: {% extends "ProyectoApp/base.html" … -
Choosing the scenario of using Web Sockets in standard HTTP REST API
I will be happy to get advice from more experienced developers about adding Web Sockets into my HTTP-based project. That’s the thing. I have developed the REST API based service. Everything works well enough, but… In some special cases my server needs a long time to serve client requests. It may be from 1 minute to several hours (and even days)! I implement some not-so-good algorithm to address this issue: Client sends HTTP request Server replies about registering request Client starts sending HTTP requests to get necessary data (if response does not have needed information the client sends another request and so on) That is all in a nutshell. And it seems to be a bad scenario and I am trying to integrate web sockets for adding duplex-channels in this architecture. I hope that my API will be able to send info about updated data as soon as possible without the necessity of many requests from the client. But I am a bit confused in choosing one of two ways to use web socket (WS). Variant A. The server only tells the client via WS that data is ready. And the client gets data by standard request-response HTTP method from … -
React/Django application in VSCode is giving me a "syntax" error, but I don't know what it means and never seen it before
I started building the front-end of the application with react and then I integrated Django and Django RF afterwards. I had a couple of problems with the initial set up, but I have been able to figure out each bug as they come, however, this one I don't really know what it means, it looks like a syntax error, but I am not sure what's causing it. When I run the server there's no problems and I actually a 200 status code 200 status code when going to localhost:8000 webpack is running and compiled successfully In my index.html I am trying yo load my JS which is in a static folder like this enter image description here but it shows me sort of like a syntax error, maybe it's not expecting that type of syntax ? When I look at my console in the browser I can see that my links have loaded, and that the script is working since it can reference where my JS file is console in the browser index.js import file problems One way to fix this is by adding type="module" in my index.html file inside the script tag, but once I do that it gives … -
How can I solve the reportMissingModuleSource by using Django and docker-compose without creating a virtual environment?
I've tried to create a new project with Django and docker-compose without creating virtual environment. But now, when I want to start coding in VS Code, I get the reportMissingModuleSource. For example in mysite/urls.py "Import "django.contrib" could not be resolved from sourcePylance" I'm trying to search more to find a solution! -
What is the best index for a "last modified by user" query
I have a Django query like Posts.objects.filter(user=user).order_by('-last_modified') What is the best type of index to support this query? I see two options: Index(fields=['user_id', '-last_modified']) Index(fields=['-last_modified']) Given that Django automatically indexes foreign keys such as user_id, is there any benefit to 1) vs 2)? It seems like 1) would result in fewer items being traversed by the DB, but maybe DBs are "smart enough" to join two separate indexes together and as a result the advantage will be minimal. My question is theoretical in nature: which index is the better option, in principle? -
raise ImproperlyConfigured(msg)
raise ImproperlyConfigured(msg) In "additional_app", in "models.py": from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(max_length=500, blank=True) profileimg = models.ImageField(upload_to='profile_images', default='btm-banner.png') location = models.CharField(max_length=100, blank=True) def __str__(self): return self.user.username I have created 'media_folder' in "additional_app" and put into img 'btm-banner.png' to django load it if user dont load self picture in profile. Also i write in settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Also in 'main_app', in urls.py: from django.conf import settings from django.conf.urls.static import static urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Now i want make 'migration' In Terminal: S:\Programms\Projects\social_app\main_app> py manage.py makemigration Enter Result: django.core.exceptions.ImproperlyConfigured: additional_app.apps.AdditionalAppConfig.default_auto_field refers to the module 'django.db.media .BigAutoField' that could not be imported. -
JWT cookie from Django backend not working after deploy
I have written a web app, the backend is in Django using django_rest_framework utils and the frontend is in React.js An authentication is based on JWT token stored in cookies and localStorage. It was working fine when both sides were on the localhost, but after I deployed frontend and backend on the remote server, a Django cannot set cookie in the frontend domain. Here's my code from LoginView in Django: `class LoginView(APIView): def post(self, request): username = request.data['login'] password = request.data['password'] user = authenticate(username=username, password=password) if user is not None: payload = { 'id': user.id, 'username': user.username, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=3600), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.set_cookie(key='jwt', value=token, httponly=False) response.data = { 'jwt': token, 'username': user.username, 'userId': user.id } return response response = JsonResponse({"message": "An issue occured during the authentication process."}) response.status_code = 500 return response` settings.py CORS_ORIGIN_WHITELIST = [ ... 'https://<MY FRONTEND>.azurewebsites.net' ... ] CSRF_TRUSTED_ORIGINS = [ ... "https://<MY FRONTEND>.azurewebsites.net" ] CORS_ALLOWED_ORIGINS = [ ... "https://<MY FRONTEND>.azurewebsites.net" ] CORS_ALLOW_CREDENTIALS = True CSRF_USE_SESSIONS = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' SESSION_COOKIE_DOMAIN = '.azurewebsites.net' CORS_ALLOW_HEADERS = list(default_headers) + ['Set-Cookie'] After logging in on my frontend app, I cannot … -
Simplify function code while maintaining readability
This code works, but seems too redundant to me. Is it possible to somehow simplify it while maintaining functionality and readability? has_videos = self.request.query_params.get('has_videos') if has_videos: if has_videos == 'true': entries = User.objects.filter(videos__isnull=False) elif has_videos == 'false': entries = User.objects.filter(videos__isnull=True) else: entries = User.objects.all() I tried to write in one line using the ternary operator, but the readability disappeared completely entries = Pet.objects.all() if has_photos not in ['true', 'false'] \ else Pet.objects.filter(photos__isnull=False) if has_photos == 'true' \ else Pet.objects.filter(photos__isnull=True) -
AttributeError at type object 'Services' has no attribute 'app'
I newly started to develop Django. I want to connect my python algorithm and Django web ui so I tried to connect both of them in views.py but I encountered a problem. It says AttributeError at type object 'Services' has no attribute 'app' but I declared it in the queryOnMetadataModel.init. I don't know what is wrong. Could someone help me? These are my code snippets; queryOnMetadataModel.py from Neo4jConnection import App import json class Services:` def __init__(self): uri = "neo4j+s://a50f760a.databases.neo4j.io:7687" user = "neo4j" password = "password" self.app = App(uri, user, password) def find_node_type(self,nodeName): node_type = self.app.find_node_type(nodeName) self.app.close() return node_type views.py from django.shortcuts import render from BitirmeTeziSourceCode.queryOnMetadataModel import Services import sys sys.path.append(".") # Create your views here. def home(request): data = Services.find_node_type(Services , 'Region') nodes = { "nodes" : data } return render(request , "index.html" , nodes) urls.py from django.urls import path from . import views urlpatterns = [ path("" , views.home) ] Error Image I want to access output of Services.find_node_type(Services , 'Region') from index.html -
Django - Receive Webhooks from WhatsApp Cloud Api
I'm trying to create a chat application with the WhatsApp Cloud API and I'm stuck on how to handle webhooks. Should I do it with websockets or is there another way to do it? I already tried with django-channels but I don't know how to receive the webhooks. If django-channels is the best option, could you tell me how I can receive the webhooks or point me to a tutorial. Currently I already have the sockets implemented and they connect without problems from channels.generic.websocket import JsonWebsocketConsumer class ChatConsumer(JsonWebsocketConsumer): """ This consumer is used to show user's online status, and send notifications. """ def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.room_name = None def connect(self): print("Connected!") self.room_name = "home" self.accept() self.send_json( { "type": "welcome_message", "message": "Hey there! You've successfully connected!", } ) def disconnect(self, code): print("Disconnected!") return super().disconnect(code) def receive_json(self, content, **kwargs): print(content) return super().receive_json(content, **kwargs) -
Django: After saving the Order and deleting the cart, Order looses information of ordered items
I want the cart items to be saved in each order. But after the cart is deleted, "service_items" becomes empty. Steps: Add items to the cart Save order Delete cart I think service_items = models.ManyToManyField(Cart) is causing the issue, but I don't know how to fix it. Current Order object after saving: { "id": 1, "customer": { "id": 1, "first_name": "Some", "last_name": "User", "email": "someuser@gmail.com", "phone_number": "+817056781234", "member_date": "2023-01-28T14:38:43.196580Z" }, "status": false, "total": "15.00", "order_date": "2023-01-28T16:05:11.704636Z", "delivery_date": "2023-01-31T12:52:16.193078Z", "advance_payment": "9.00", "payment_method": "cash", "due_payment": 6.0, "service_items": [] } Expected outcome: { "id": 1, "customer": { "id": 1, "first_name": "Some", "last_name": "User", "email": "someuser@gmail.com", "phone_number": "+817056781234", "member_date": "2023-01-28T14:38:43.196580Z" }, "status": false, "total": "15.00", "order_date": "2023-01-28T16:05:11.704636Z", "delivery_date": "2023-01-31T12:52:16.193078Z", "advance_payment": "9.00", "payment_method": "cash", "due_payment": 6.0, "service_items": [ { "id": 1, "service_item": { "id": 1, "item_name": "Black Shirt", "description": "Half and Full Sleeve Black Shirts.", "wash_price": "3.00", "stain_treatment_price": "1.00", "iron_price": "2.00", "dry_wash_price": "4.00", "category": { "id": 2, "title": "Shirt" } }, "is_wash": false, "is_stain_treatment": true, "is_iron": false, "is_dry_wash": true, "quantity": 3, "unit_price": "5.00", "price": "15.00", "customer": 1 } ] } models.py class ServiceItem(models.Model): item_name = models.CharField(max_length=200) description = models.TextField(null=True) wash_price = models.DecimalField(max_digits=6, decimal_places=2, null=False, default=0) stain_treatment_price = models.DecimalField(max_digits=6, decimal_places=2, null=False, default=0) iron_price = models.DecimalField(max_digits=6, decimal_places=2, … -
Django: subtract the total from two table group by common group name
I'm trying to get the result from exchange table (incoming) (-) expense table grouped by account but the result is multiplying the Sum * the number of rows in the other table. class Account(models.Model): trip = models.ForeignKey(Trip, default=1, on_delete=models.SET_DEFAULT) description = models.CharField('Description', max_length=254) class Exchange(models.Model): buy_date = models.DateField(verbose_name='Buy Date') quantity = models.DecimalField(('Quantity'), max_digits=32, decimal_places=2, blank=True, null=True) quote = models.DecimalField(('Quote'), max_digits=32, decimal_places=2, blank=True, null=True) total = models.DecimalField(('Total'), max_digits=32, decimal_places=2, blank=True, null=True) account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT) class Expense(models.Model): start_date = models.DateTimeField(verbose_name='Date') amount = models.DecimalField(('Amount'), max_digits=32, decimal_places=2, blank=True, null=True) fee = models.DecimalField(('Fee'), max_digits=32, decimal_places=2, blank=True, null=True, default=0) total = models.DecimalField(('Total'), max_digits=32, decimal_places=2, blank=True, null=True, default=0) account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT) I've tried to perform the following operation: result = ( Account .objects .values('description') .filter(created_by=user) .filter(trip=selectedtrip_id) .filter(exchange__quantity__gt=0) .annotate(exchange_total=Sum('exchange__quantity'), expense_total=Sum('expense__total') ) .annotate(account_remain=F('exchange_total') - F('expense_total')) .order_by('description') ) The idea is to know how much left on the account. But the problem is when you do the operation like this, the result is the total multiplied by the number of rows on the expense table. Account 1,Account01 2,Account02 Exchange 2023-01-01, 100, 5.0, 500, 1 2023-01-01, 100, 4.9, 490, 1 2023-01-01, 200, 5.1, 510, 1 2023-01-01, 100, 5.0, 500, 2 Expense 2023-01-10, 10, 1, 11, 1 2023-01-11, …