Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't create in related tables in django using serializers
Please, help! I need create a stock database postgresQL. I use the command in Visual Studio Code. But I have error on string "StockProduct.objects.create" in serializers.py. The stock is created in base, but without products in this stock. command in Visual Studio Code: ### # create a stock POST {{baseUrl}}/stocks/ Content-Type: application/json { "address": " stock_ address ru3", "positions": [{"product": 2, "quantity": 250, "price": 120.50}, {"product": 3, "quantity": 100, "price": 180}] } serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('title', 'description') class ProductPositionSerializer(serializers.ModelSerializer): class Meta: model = StockProduct fields = ('quantity', 'price') class StockSerializer(serializers.ModelSerializer): positions = ProductPositionSerializer(many=True) #id = serializers.IntegerField() # configure the serializer for the warehouse class Meta: model = Stock fields = ('address', 'positions') def create(self, validated_data): positions = validated_data.pop('positions') # create stock stock = super().create(validated_data) for position in positions: StockProduct.objects.create(stock=stock, product_id=position['product'], price=position['price'], quantity=position['quantity'])# 1.Variant #StockProduct.objects.create(stock=stock, **position) # 2. variant "logistic_stockproduct" relation violates NOT NULL restriction # defaults = {'price'=position['price'], 'quantity'=position['quantity']}) #product=position['product'], price=position['price'], quantity=position['quantity']) # StockProduct.objects.create(position) #position=position # StockProduct.objects.create(stock('id'), position) #StockProduct.objects.create(positions) # quantity = position.pop('quantity') # price= position.pop('price') # StockProduct.objects.create(quantity=quantity, price=price) return stock variant Error # 1 variant Error . line 36, in create StockProduct.objects.create(stock=stock, product_id=position['product'], price=position['price'], quantity=position['quantity']) KeyError: 'product' # 2. variant: DETAIL: The … -
Using JavaScript onclick function to change innerHTML to form field
I am trying to use the JavaScript onclick() function to change a piece of HTML to a Django Model Form field when clicked? Using the code below, I would expect that when the {{ tasks.owner }} is clicked, the html with id "task_owner" would change to {{ task_update_form.owner }}. My Django template is below: <script> function OwnerUpdate() { document.getElementById("task_owner").innerHTML = "{{ task_update_form.owner }}"; } </script> <p id = "task_owner", onclick = "OwnerUpdate()"> {{ tasks.owner }} </p> If I use the below code - substituting {{ task_update_form.owner }} with "Test" it works perfectly. <script> function OwnerUpdate() { document.getElementById("task_owner").innerHTML = "Test"; } </script> <p id = "task_owner", onclick = "OwnerUpdate()"> {{ tasks.owner }} </p> I have also tested it using non-form context from my views.py and it works. {{ task_update_form.owner }} works fine when inserted into the Django template normally. My experience with JavaScript is limited and I would be grateful for any help. -
Query Django custom user model with many-to-many field
I'm very new at Django. I have a custom user model: accounts\models.py: from django.contrib.auth.models import AbstractUser from django.db import models from tradestats.models import Webhook class CustomUser(AbstractUser): webhook = models.ManyToManyField(Webhook, blank=True) I have a tradestats app with a Webhook model: tradestats\models.py from django.db import models class Webhook(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) name = models.CharField(verbose_name='Webhooks name', max_length=50, null=False, blank=False) url = models.URLField(max_length=255, null=False, blank=False, unique=True) def __str__(self): return self.name class Meta: ordering = ['name'] I have a class based View. In this View I like to query the logged in user all Webhooks url field and pass to render() as a context. tradestats\view.py: context = { 'form': form.cleaned_data, 'variable': value1, 'variable2': value2, } return render(request, template_name='renko/renko_calculate.html', context=context) How can I query the webhook.urls and pass into context? Thank you so much. -
I create speech to speech translation using python how can deploy on flask to take input from microphone bcz after deployment PyAudio not working
I create speech to speech translation continously using thread using python how can deploy on flask to take input from microphone because after deployment PyAudio not working -
How to check if a django model attribute is of type ManyToMany
I have a django model in which I am inspecting the fields types and I want to check if a field is a ManyToMany field. When I call the type(attribute) function however, the returned type is a ManyRelatedManager object and not a ManyToManyField. This is a bit of a problem because I can't use the isinstance(attribute, ManyRelatedManager) because from what I see in the source code, this class is in a closure context and can't be accessed externally. How would I check if a field in django is of type ManyToMany? I checked out this answer but this doesn't seem to be my scenarion, I don't care what is the model of the ManyToMany I want to know if it is a many to many -
DRF - serializer for list of dictionaries
I've a serializer class which return "single" data well, like: class MySerializer(serializers.Serializer): num: Decimal = serializers.DecimalField(max_digits=10, decimal_places=4, required=True uid: str = serializers.CharField(max_length=30, required=True) . I'd like to add a parameter (other) to this serializer which would return list of dictionaries, but I can't find out how to do it. The structure of other would look like this: [ {'p1': int, 'p2': int, 'p3': {another dict which has already a serializer class} } ] What would be the way to achieve this? If I add serializers.DictField or serializers.ListField I always got back "'list' object has no attribute 'items' AttributeError" or "Object of type PoCo is not JSON serializable TypeError" where PoCo is a class of mine. Thanks. -
Django View Unit-Test: assertHTML selector 'body' is empty
I am trying to Unit-Test my Django-Views via pytest -s my_view.py. Currently I am testing one like this: table_selector = CSSSelector("table.tableClass tbody tr") response = self.client.get(reverse("endpoint", args=(object.id,)), follow=True) with self.assertHTML(response, "body") as (body,): print(response.content) # shows HTML as expected print(body.text) table_rows = table_selector(body) print(table_rows) # empty array print(body.text) gives me this output: basically just empty spaces / new lines even though response.content contains a <body>-tag! How is this possible? Any ideas why this doesn't work? -
D3.js Fix Date Issue on Line Graph - Django as Backend
I am following some examples of d3.js to plot graphs. For reference here is the link. Following is the code where I've used the LineChart function to build the plot. With Django as backend. <!DOCTYPE html> {% load static %} <html> <script src="https://d3js.org/d3.v6.js"></script> <body> <h1> Hello! </h1> <div id="chart"></div> </body> <script> // set the dimensions and margins of the graph const margin = { top: 10, right: 30, bottom: 30, left: 60 }, width = 460 - margin.left - margin.right, height = 400 - margin.top - margin.bottom; // Copyright 2021 Observable, Inc. // Released under the ISC license. // https://observablehq.com/@d3/line-chart function LineChart(data, { x = ([x]) => x, // given d in data, returns the (temporal) x-value y = ([, y]) => y, // given d in data, returns the (quantitative) y-value defined, // for gaps in data curve = d3.curveLinear, // method of interpolation between points marginTop = 20, // top margin, in pixels marginRight = 30, // right margin, in pixels marginBottom = 30, // bottom margin, in pixels marginLeft = 40, // left margin, in pixels width = 640, // outer width, in pixels height = 400, // outer height, in pixels xType = d3.scaleUtc, // the … -
Password must be a string or bytes, got list Django Rest Framework
I have an API that has a createaccount endpoint. I pass a password when creating the user and the password is passed as string. However, when it is passed to the serializer it comes out as a list, which causes this error: Password must be a string or bytes, got list this error also duplicates itself to my other two attributes, username and account_type as seen below. I have had to do list comprehension by getting the first element of the lists to get the values which I feel is the incorrect way of dealing with this issue. Here is my models.py for the Account model with its associated Manager: from django.db import models import django.contrib.auth.models as auth_models class AccountManager(auth_models.BaseUserManager): def create_user(self, username, account_type, password=None): if not account_type: raise ValueError("Users must have an account type") if not username: raise ValueError("Users must have a username") requested_account_type = account_type[0] user = self.model(username=username, account_type=requested_account_type) user.set_password(password[0]) user.save(using=self._db) return user def create(self, username, account_type): if not account_type: raise ValueError("Users must have an account type") if not username: raise ValueError("Users must have a username") requested_account_type = account_type[0] user = self.model(username=username, account_type=requested_account_type) user.save(using=self._db) return user def create_superuser(self, username, password, account_type="jool-admin"): user = self.create_user( password=password, username=username, account_type=account_type ) … -
Image not visible on webpage despite adding every crucial code
I am trying to upload my image to make it visible on the webpage but it isnt happening,the alt="no image found" comes.I am doing a CRUD project using serializers this surely means that there is no problem with the paths that I have inserted but the problem is there elsewhere but I am unable to figure it out and I have tried many times. below are the show and insert function def show(request): showall = Products.objects.filter(isactive=True) print("show all data:",showall) serializer = POLLSerializer(showall,many=True) data = serializer.data for i in range(len(data)): product = Products.objects.filter(id=data[i]['id']).first() data[i]['categories'] = product.categories.__str__() data[i]['color'] = product.color.__str__() data[i]['size'] = product.size.__str__() data[i]['sub_categories'] = product.sub_categories.__str__() context = {"data":data} return render(request,'polls/product_list.html',context) def insert(request): data = {} if request.method == "POST": print('POST',id) data['categories'] = request.POST.get('categories') data['sub_categories'] = request.POST.get('sub_categories') data['color'] = request.POST.get('color') data['size'] = request.POST.get('size') data['title'] = request.POST.get('title') data['price'] = request.POST.get('price') data['sku_number'] = request.POST.get('sku_number') data['product_details'] = request.POST.get('product_details') data['quantity'] = request.POST.get('quantity') data['image'] = request.FILES['image'] form = POLLSerializer(data=data) print(form) if form.is_valid(): print('form after valid:',form) print("error of form:",form.errors) form.save() messages.success(request, "Record Updated Successfully...!:)") return redirect("polls:show") else: print('form not valid') print(form.errors) if request.method == "GET": print('POST',id) category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict, many=True) sub_category_dict = SUBCategories.objects.filter(isactive=True) sub_category = SUBCategoriesSerializer(sub_category_dict,many=True) color_dict = Colors.objects.filter(isactive=True) color = ColorsSerializer(color_dict,many=True) size_dict = Size.objects.filter(isactive=True) … -
I want to click a Tkinter button and then export the searched item to excel file, how can I do that?
def print_area(self, txt): try: con = pymysql.connect(host='localhost', user='root', password='', db='philanthropy') cur = con.cursor() cur.execute("select * from istavrity where familycode LIKE '%"+self.var_search.get()+"%'") row=cur.fetchall() for i in row: fName = i[1] if len(row)>0: row_list = [] columns = ('S.N.', 'Family Code', 'Family Name', 'Ritwik', 'Swastyayani', 'Family Name', 'Ritwik', 'Swastyayani', 'FamilyCode', 'Family Name', 'Ritwik', 'Swastyayani', 'FamilyCode', 'Family Name', 'Ritwik', 'Swastyayani', 'ravv') self.employee_tree.delete(*self.employee_tree.get_children()) for i in row: self.employee_tree.insert('',END,values=i) row_list.append(i) treeview_df = pd.DataFrame(row_list, columns = columns) print(treeview_df) treeview_df.to_excel(f"excel_backup/{fName}.xlsx") else: self.employee_tree.delete(*self.employee_tree.get_children()) except Exception as ex: messagebox.showerror("Error",f"Error due to {str(ex)}") The search area code is # btn_search = Button(root, text="Search", font=("times new roman", 12), bg="white",fg="black").place(x=800,y=5, height=20) self.txt_search = Entry(root,textvariable=self.var_search, font=("goudy old style",15,'bold'), bg="white",fg="blue") self.txt_search.place(x=870,y=5,height=20,width=250) self.txt_search.bind("<Key>", self.search) And the button code is: self.btn_print = Button(root,text="Print", font=("times new roman", 15), bg="red", fg="white") self.btn_print.pack() The problem is, just by searching the fcode, it gets exported without clicking button. -
Error for my model with ManyToManyField in Django
I am working for a personal project that is using an API and having user authentication with JWT (but used in serializer). I wanted to implement ManyToManyField for user and city but it doesn't work properly. This is the extended model I have found . I want that the UserSearchLocation to store the City and when logged in to see the city, while other users will not see it until the search same city. models.py from django.db import models from django.contrib.auth.models import User class UserSearchLocation(models.Model): id = models.AutoField(primary_key=True, editable=False) search = models.CharField(max_length=50, null=True) user = models.ManyToManyField(User, related_name="my_cities", blank=True) def __str__(self): return self.search class City(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(UserSearchLocation, on_delete=models.SET_NULL, null=True) id = models.AutoField(primary_key=True, editable=False) location = models.CharField(max_length=85) def __str__(self): return f'{self.location}, {self.country_code}' def save(self, *args, **kwargs): self.location = self.location.capitalize() self.country = self.country.capitalize() self.country_code = self.country_code.capitalize() return super(City, self).save(*args, **kwargs) serializers.py class ForecastSerializer(serializers.ModelSerializer): id = serializers.IntegerField() city = serializers.StringRelatedField() country_code = serializers.StringRelatedField() country = serializers.StringRelatedField() class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields = "__all__" class UserSearchLocationSerializer(serializers.ModelSerializer): class Meta: model = UserSearchLocation fields = "__all__" To add in localhost/admin/ a CitySearchLocation works, but when to add a City I have this error: column base_city.location does not exist … -
django.urls.exceptions.NoReverseMatch: Reverse for xxx not found. xxx is not a valid view function or pattern name
I have problem bcz i get: Powershell: django.urls.exceptions.NoReverseMatch: Reverse for 'register' not found. 'register' is not a valid view function or pattern name. Project Schematic: https://ibb.co/g39qB9k Error during template rendering: https://ibb.co/q0QkwvQ html: <section> <!-- Navbar --> <nav class="navbar navbar-expand-lg bg-dark navbar-dark "> <!-- Container wrapper --> <div class="container-fluid justify-content-center"> <!-- Navbar brand --> <a class="navbar-brand" href="{% url 'home_page' %}"> Turbine Power Web</a> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ms-auto"> {% if user.is_authenticated %} <li class="nav-item"><a class="nav-link" href="{% url 'accounts:logout' %}">Logout</a></li> <li class="nav-item"><a class="nav-link" href="{% url 'accounts:password_change' %}">Change Password</a></li> {% else %} <li class="nav-item"><a class="nav-link" href="{% url 'accounts:login' %}">Login</a></li> <li class="nav-item"><a class="nav-link" href="{% url 'accounts:user-registration' %}">Register</a></li> {% endif %} <li class="nav-item"><a class="nav-link" href="">Turbine Models</a></li> <li class="nav-item"><a class="nav-link" href="">Author</a></li> {% if user.is_company %} <li class="nav-item"><a class="nav-link" href="">My Models</a></li> {% endif %} <li class="nav-item"> Hello, {{ user.username|default:'Guest' }} </li> </ul> </div> </div> </nav> <!-- Navbar --> </section> views: def home_page(request): return render(request, 'turbineweb/home_page.html') project urls: urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls', namespace='accounts')), path('', include('turbineweb.urls')), accounts urls: app_name = 'accounts' urlpatterns = [ path('login/', CustomLoginView.as_view(redirect_authenticated_user=True, template_name='accounts/login.html', authentication_form=LoginForm), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name='logout'), path('registration/', RegisterView.as_view(), name='users-registration'), path('password-change/', ChangePasswordView.as_view(), name='password_change'), path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] turbineweb urls: app_name … -
How to fix ERR_TOO_MANY_REDIRECTS?
I'm developing a site on Django, but I got an error ERR_TOO_MANY_REDIRECTS. I think that the matter is in the views.py file. Help figure it out. P.S. already tried to delete cookie files, it didn't help( from email import message from wsgiref.util import request_uri from django.shortcuts import redirect, render from django.contrib.auth.models import User, auth from django.contrib import messages # Create your views here. def reg(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] cpassword = request.POST['cpassword'] if password == cpassword: if User.objects.filter(username=username): messages.info(request, 'Username taken') return redirect('registration') else: user = User.objects.create_user(username=username, password=password) user.save() return redirect('login') else: messages.info(request, 'Passwords not matching') return redirect('registration') return redirect('/') else: return render(request, 'registration.html') def login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username = username, password = password) if user is not None: auth.login(request, user) return redirect('/') else: messages.info(request, 'Invalid credentials') return redirect('login') else: return render(request, 'login.html') def logout(request): auth.logout(request) return redirect('/') -
xhtml2pdf use a personal Font but not view my font
I need to create a pdf and I need my own font which is present in static / font / I just don't understand how to import it. the font always remains the same and I don't know how to do it, can someone help me? <style> @font-face { font-family: 'Titolo'; src: url('/static/font/titolo.ttf') format('truetype'); } @page { size: A4 portrait; @frame header_frame { -pdf-frame-content: header; top: 10mm; width: 210mm; margin: 0 10mm; } } h1{ font-family: 'Titolo'; color: red; font-size: 4rem; margin-bottom: 0; line-height: 1; } </style> -
Django: int() argument must be a string, a bytes-like object or a number, not 'datetime.timedelta'
I would like to aggregate with a queryset and compare the difference in minutes between 2 datetime in Django. And I would like to have the result in minutes (rounded). opened_at and created_at are DateTimeField fields. @action(detail=False, methods=["get"], url_path="person-click-speed") def person_click_speed(self, request): accounts = get_account_ids(request) queryset = models.CoursePerson.objects.filter( account__in=accounts, ) data = queryset.aggregate( less_5_mint_count=Count( "uid", average_clic_time=Avg(F('emails_person__opened_at') - F('emails_person__created_at')), ) res = { 'less_5_mint_count': data['less_5_mint_count'], 'average_clic_time': round(data['average_clic_time'].total_seconds() / 60 if data['average_clic_time'] else 0), } return Response(data=res) This code works well but I need to do that directly in the aggregate (average_clic_time). -
Is there anyway to set auth token for my Django Project (Not django-rest)
hi im looking how to expire the token of user in 1hour...i guess Django uses the default time of 24Hours . -
How to make sure celery will receive our tasks?
I'm having a problem when using celery I'm handling my upload-file api with celery and sometimes it does not receive the task and my file will not upload into MINIO, And sometimes it does receive the tasks and the upload is successful. What can be the problem? And How can we make sure that celery will receive the task? I'm using Django as a backend framework. -
Form data not stored in database. What is the problem?
This form working working perfectly, class FeedBackForm(forms.Form): feedBACK = forms.CharField(widget=forms.Textarea, required=True) But this form didn't work class FeedBackForm(forms.Form): feedBACK = forms.CharField(widget=forms.Textarea, required=True) rating = forms.CharField(widget=forms.IntegerField, required=True) It is showing below error. Where did the problem occur? I checked documentation but no clue I found. AttributeError at /quick_view/11/ 'IntegerField' object has no attribute 'value_from_datadict' Request Method: POST Request URL: http://127.0.0.1:8000/quick_view/11/ Django Version: 4.0.4 Exception Type: AttributeError Exception Value: 'IntegerField' object has no attribute 'value_from_datadict' Exception Location: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\django\forms\forms.py, line 224, in _widget_data_value Python Executable: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\Scripts\python.exe Python Version: 3.9.5 Python Path: ['D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\python39.zip', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\DLLs', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\lib', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39', 'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site\\env', 'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce ' 'site\\env\\lib\\site-packages'] Server time: Wed, 13 Jul 2022 10:41:38 +0000 -
post method is not working in single page django website
I'm learning Django from youtube. now I'm practicing on a project but the problem is the youtube tutorial used multi page django website while i'm developing a single page website where if you click a menu item, it will scroll down to the section instead of opening a new page. I had created only one app. I am really confused because as I have only 2 html page( one main and another with different layout for blog), I really don't know how to mention the pages in views.py. I have connected post method to home function but the post isn't working. views.py: from django.shortcuts import render, HttpResponse from django.http import HttpResponse # Create your views here. def home(request): if request.method == "POST": print("This is post") return render(request, 'index.html') def blog(request): if request.method=="POST": print("This is post") return render(request, 'blog-single.html') urls.py from app: from django.contrib import admin from django.urls import path, include from portfolio import views urlpatterns = [ path('admin/', admin.site.urls), path('home', views.home, name='home'), ]``` -
Django ORM query with user defined fields
I'm trying to create an Django ORM query to replace a really messy raw SQL query i've written in the past but i'm not sure if Django ORM can let me do it. I have three tables: contacts custom_fields custom_field_data What I'm hoping to be able to do with the ORM is create an output as if i've queryied one single table like this: Is such a thing possible with the ORM? -
restoring dump backup not working with dj rest auth EmailAddress model
I use dj rest auth to register and login users and i have successfully made and restored a dump backup from my database with django-dbbackup my problem is when i restore backup , the data saved in EmailAddress model from dj rest auth is not restoring which means the login for users is not working and i get the error EmailAddress matching query does not exist and when i login the admin panel and add the emailaddress manually in EmailAddress it works again!how can i create a backup with EmailAddress model as well ? -
django.db.utils.OperationalError: (1050, "Table 'accounts_profile_branch' already exists")
Found another file with the destination path 'admin/js/cancel.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. -
Getting 499 error while GET request and "Ignoring connection EPIPE" at Gunicorn. Django +NGINX + Gunicorn + INGRESS
I am trying to migrate my application to kubernetes from the docker host. The app is built using Django, Nginx, Gunicorn. The app is loading perfectly in k8s. Container is able to connect to database (verified via telnet). App is able to run multiple GET requests successfully, But one GET request is giving below error: "GET /MyApp/URL/?=10 HTTP/1.1" 499 0 "https:///MyApp/URL/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36" And in Gunicorn error logs I get below error: [2022-07-13 08:08:41 +0000] [107] [DEBUG] GET /MyApp/URL/ [2022-07-13 08:21:51 +0000] [105] [DEBUG] Ignoring connection epipe [2022-07-13 08:37:36 +0000] [107] [DEBUG] Ignoring connection epipe How to resolve this? Adding all the configuration I have done at Ingress, Nginx, Gunicorn level: Ingress.yaml apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: app-name namespace: {{ .Release.Namespace }} annotations: nginx.ingress.kubernetes.io/proxy-connect-timeout: "1000" nginx.ingress.kubernetes.io/proxy-read-timeout: "1000" nginx.ingress.kubernetes.io/proxy-send-timeout: "1000" nginx.ingress.kubernetes.io/allow-backend-server-header: "true" spec: rules: - host: {{ .Values.ingress_hostname }} http: paths: - backend: service: name: app-service port: number: 443 path: / pathType: ImplementationSpecific tls: - hosts: - {{ .Values.ingress_hostname }} secretName: {{ .Values.tls.name }} service.yaml apiVersion: v1 kind: Service metadata: name: app-service namespace: {{ .Release.Namespace }} labels: {{- include "app-name.labels" . | nindent 4 }} spec: type: ClusterIP ports: - … -
Django aggregate with expressions between ForeignKey (and not) values
I'm having these models class Car(models.Model): liter_per_km = models.FloatField(default=1.0) class DrivingSession(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) km = models.FloatField(default=1.0) Is there a way using Django features (e.g aggregate) to calculate the same total_liters like in code below? total_liters = 0.0 for session in DrivingSession.objects.all(): total_liters += (session.km * session.car.liter_per_km)