Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
show price based on product by selecting form option
I have a model for product and purchase. I want whenever a user select product name, the field of price will be auto filled. Thanks in advanced. models.py class ProductDetails(models.Model): id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=100, unique=True) purchase_price = models.DecimalField(max_digits=7, decimal_places=2) dealer_price = models.DecimalField(max_digits=7, decimal_places=2) retail_price = models.DecimalField(max_digits=7, decimal_places=2) remarks = models.CharField(max_length=255, blank=True) def __str__(self): return self.product_name class TemporaryData(models.Model): id = models.AutoField(primary_key=True) product_id = models.ForeignKey(ProductDetails, on_delete=models.CASCADE) price = models.DecimalField(max_digits=7, decimal_places=2) quantity = models.IntegerField() amount = models.DecimalField(max_digits=7, decimal_places=2) def __int__(self): return self.id Forms.py class TempoForm(forms.ModelForm): class Meta(): model = TemporaryData fields = '__all__' widgets = { 'product_id':forms.Select(attrs={'class': 'form-control', 'id': 'select1'}), 'price': forms.TextInput(attrs={'class': 'form-control', 'id': 'select2'}), 'quantity': forms.TextInput(attrs={'class': 'form-control'}), 'amount': forms.TextInput(attrs={'class': 'form-control'}), } Views.py def tempoData(request): form = TempoForm() tempo_data = TemporaryData.objects.order_by('id') if request.method == 'POST': form = TempoForm(request.POST) if form.is_valid(): form.save(commit=True) return redirect('purchase_form') else: print('Please fill up the form accurately') return render(request, 'product/purchase_form.html', {'form': form, 'tempo_data': tempo_data}) I need the price data from database as per product ID. I need full code so you can also provide me any use full link. Thanks. -
DropzoneJS formData is empty when trying to append new data for S3 Direct upload
I'm working with Django and DropzoneJS, trying to get direct client-to-s3 uploads to work. Currently, I keep getting a 405 Method Not Allowed, though I've specifically set my CORS policy to allow POST. I am dynamically settings two fields on the file object, rdata and rurl, which contain the data necessary to POST to S3, and the URL to post to. rurl is used to POST to, rdata contains all the other stuff like acl: public-read and Content-Type My Dropzone code: <div id="dropzone" class="dropzone"></div> <script> var myDropzone, sendingFiles = false, varMaxFiles = 4; loadJS('vendor/dropzone.min.js', function () { Dropzone.autoDiscover = false; myDropzone = new Dropzone('#dropzone', { {% if existing_files %} init: function () { var myDropzone = this; // Handle displaying existing files }, {% endif %} accept: function (file, done) { file.postData = []; var xhr = new XMLHttpRequest(); xhr.open("GET", "{% url 'sign-s3' experience.id %}?file_name=" + file.name + "?file_type=" + file.type); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { var response = JSON.parse(xhr.responseText) debugger; file.rdata = response.data file.rurl = response.url } } } xhr.send(); done(); }, url: "/", acceptedFiles: ".jpg,.jpeg,.png,.avi,.mov,.m4v,.mp4,.mpeg", addRemoveLinks: true, autoProcessQueue: false, autoQueue: true, maxFiles: varMaxFiles, parallelUploads: 5, thumbnailWidth: 120, maxFilesize: … -
How should I manage my images for my django app
Here I am once again asking a question that might seem stupid: I am new to web development. So far I've made some practice projects with Django and I've deployed two projects so far as github pages but they were simple static websites (no django). Now I'm making a web application for my mom's business with Django. I don't know what I should do with all the images I need for the website. In the past I have uploaded all jpg and png images to imgur and copied the link in my static websites html But now I have more images and I am going to pay for a server for them application. I have two types of images: Images that will always appear on the page. Because that's part of the design Images that the admin can upload when creating a new post for the page So my question is: Should I have all images in the statics folder for my application? And call them like this: <img src="{% static 'website/images/home-slider/myimage.css' %}"> And for the other images should I save a similar path in the database? I just have no idea if things should be done different for production -
django - adding object to manytomany: Cannot add "<object>": the value for field "other object" is None
I am using a form to retrieve a TextField. I then parse each line of the textfield to create students and save a Student object. Finally I add students to a Classroom object. This worked when student was a foreignkey to classroom. I changed this relationship to a ManyToMany relationship and now I get the error: Cannot add "<Student: name>": the value for field "student" is None. Models class Student(models.Model): student_first = models.CharField(max_length=30) student_last = models.CharField(max_length=30) nickname = models.CharField(max_length=31) fullname = models.CharField(max_length=60) attend = models.BooleanField(default=True) do_not_pick = models.BooleanField(default=False) student_number = models.IntegerField() email = models.EmailField(max_length=50) class Classroom(models.Model): """The gradebook is split into courses, classes and students""" classroom_name = models.CharField(max_length=10) course = models.ForeignKey(Course, on_delete=models.CASCADE) students = models.ManyToManyField(Student) View def addmultistudent(request, classroom_id): """Add multiple students at once.""" classblock = get_object_or_404(Classroom, pk=classroom_id) context = {'classblock': classblock} if request.method == 'POST': form = StudentInputForm(request.POST) if form.is_valid(): s = form.save() input_list = [] input_list = s.name_list.split('\n') # the for returns a list of students with student number, fisrt_name, last_name in each line for line in input_list: # remove the carriage return line = line.strip('\r') # removes double quotes line = line.translate({ord(c): None for c in '"'}) # ignore the first line which is a header starting … -
How can I create a form with unknown number of columns and rows?
I don't know if I will be able to explain this very well, so please bear with me, and I will update where/when needed as much as I can. I have a Django app that is designed to take in data from users for products that we need to configure. The products are split into main categories of main products, which are then further split by customer. Main products have default settings, and customer products have SOME of these settings changed, plus some others not listed by the main product. Each customer may have multiple variations of the product too. Example of products: Main Product A | |-> Customer A Product A1 |-> Customer A Product A2 | |-> Customer B Product A1 |-> Customer B Product A2 Main Product B | |-> Customer A Product B1 |-> Customer A Product B2 | |-> Customer B Product B1 |-> Customer B Product B2 What I need/want, is a table for staff to enter the needed settings for a given customer, without the app knowing how many settings are needed, and how many customer products there are, in advance. Example: Setting Product A1 + Low Power TRUE Delayed Start 5 seconds … -
Django how to get inbound data of html fields when not using froms in views?
I am using Django default login in my views. When user typing wrong password or username then it's showing the error message but the data those entered by user are disappeared. I want to to keep the wrong data in my html username and password fields. here is my views.py: def login_view(request): if request.user.is_authenticated: return redirect('blog:my-account') else: if request.method == 'POST': username = request.POST.get('username') password =request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('blog:my-account') elif username == "": messages.info(request, "Please enter username") elif password == "": messages.info(request, "Please enter password") else: messages.info(request, "Please enter right password or username") context = {} return render(request, 'members/login.html',context) my html fields for username and password: <input type="text" name="username" id="your_name" placeholder="username"/> <input type="password" name="password" id="your_pass" placeholder="Password"/> I tried this but didn't work : ..... else: messages.info(request, "Please enter right password or username") ......... # then trying this code for get inbound value inboud_username = username inboud_password = password context = {'inboud_username':inboud_username,'inboud_password':inboud_password} return render(request, 'members/login.html',context) #html <input type="text" name="username" id="your_name" placeholder="username" {% if inboud_username.is_bound %}value="{{ inboud_username.value }} {% endif %}"/> <input type="password" name="password" id="your_pass" placeholder="Password" {% if inboud_password.is_bound %}value="{{ inboud_password.value }} {% endif %}"/> -
Why do I receive a 403 status when I make this request?
I'm developing a web app in django and vue js. I write a function to make a request to the api, and until now everything gone well, but in my first post request I have a problem: Here there are: 1.question editor component 2. the function to connect at the api 3. the api 4. the permission classes I receive a 403 status code. -
DRF: No param in validated_data
Each account like client has a user foreign key. So my frontend send user as json string, with params, like: '{"username": "fdfdf"}'. So when I create a user, there's a 'user' param in the serializer validated_data (ClientCreateSerializer) When I update a user, there's NO a 'user' param in the serializer validated_data (ClientSerializer) My code: class UserCreateSerializer(ModelSerializer): email = serializers.EmailField(validators=[ UniqueValidator(queryset=User.objects.all()) ]) username = serializers.CharField( validators=[UniqueValidator(queryset=User.objects.all())], required=False # if there's no username, set as email ) first_name = serializers.CharField( max_length=30, required=False ) class Meta: model = User fields = ('id', 'username', 'email', 'password', 'first_name', 'last_name') class AbstractAccountSerializer(serializers.ModelSerializer): user = UserCreateSerializer() def update(self, instance, validated_data): """Also save User object data""" # HERE'S NO 'user' IN VALIDATED_DATA return super().update(instance, validated_data) class ClientSerializer(AbstractAccountSerializer): class Meta: model = Client fields = [..., 'user'] class ClientCreateSerializer(ClientSerializer): class Meta(ClientSerializer.Meta): pass def create(self, validated_data): # HERE'S A 'user' IN VALIDATED_DATA user = create_user(**validated_data.pop('user')) return create_client(**validated_data, user=user) I send PATCH request to update a client (ClientSerializer) with these parameters: {"user": {"username": "Alex", "last_name": "Terrible"}} And in my update method, there's just no 'user' in validated_data -
Why decorator @property return id in Django
In my models.py I have @property decorator - but it returns me id of model. I wrote method in this decorator but it is does not work: @property def replace_name(self): if not self.name: if self.middle_name: return self.full_name if not self.middle_name: return self.address My html template: {{ object.person.replace_name }} What does it wrong here? -
Deploying a full-stack web application (Django and Angular)
I built a nice full-stack application using Django as back-end and Angular as front-end with login functionality. I feel like it would help me tremendously in landing a full-stack developer position if I was able to deploy it and show it during the interview. However, I am finding trouble finding the documentation on how I would do so. Any suggestion would be greatly appreciated. Thank you!!! -
Django not able to locate static files
i am frustrated now ..been trying this for 2 days now.. tried every thing Django is not importing static files My settings STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'my_blog'/'static', ] my imports href="{% static 'css/bootstrap.css' %}" rel="stylesheet" type="text/css" /> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet" type="text/css" /> <script src="{% static 'js/bootstrap.min.js' %}"></script> <link href="{% static 'base.css' %}" rel="stylesheet" type="text/css" /> -
Django: error_messages not overriding default error messages
I am a beginner in Django, so sorry if this is a dumb question. I am trying to override the default error messages with custom messages, that I define in error_messages={...}. But the error messages are not overriding Here is my form.py using ModelForm. My model is a custom User model. class SignupForm(ModelForm): password = CharField( min_length=6, required=True, label='Password', help_text='Password should be minimum 6 characters long, including alpha numeric value', widget=PasswordInput(attrs={ 'class': 'input--password', 'type': 'password', 'aria-label': 'Enter a password', 'placeholder': 'Enter password', 'title': 'Enter password' }), error_messages={ 'required': _('Password is required'), 'min_length': _('Password is too short') } ) class Meta: model = User fields = ('username', 'email_address', 'password') labels = { 'username': _('Username'), 'email_address': _('Email Address'), 'password': _('Password') }, error_messages = { 'username': { 'unique': _('username has already been taken'), 'required': _('username is required'), 'max_length': _('username is too long') }, 'email_address': { 'unique': _('Email address has already been taken'), 'required': _('Email address is required'), 'invalid': _('Please enter a valid email address') }, }, widgets = { 'username': TextInput(attrs={ 'class': 'input--username', 'placeholder': 'Enter username', 'aria-label': 'Enter a username', 'title': 'Enter username', 'type': 'text' }), 'email_address': TextInput(attrs={ 'class': 'input--email', 'placeholder': 'Enter email', 'aria-label': 'Enter a email', 'title': 'Enter email', 'type': 'email' }) … -
Why is my_task.delay() working from shell but not apache/wsgi
Celery worker and beat are working fine. Site loads fine except when I call a url that passes a task to Celery. This is my WSGI file. import os import sys import dotenv from django.core.wsgi import get_wsgi_application dotenv.load_dotenv() def addpath(path): if path not in sys.path: sys.path.insert(0, path) addpath('/opt/ada') os.environ['DJANGO_SETTINGS_MODULE'] = 'ada.settings' os.environ['PYTHONPATH'] = '/opt/ada' os.environ['CELERY_LOADER'] = "django" I don't understand this error. mod_wsgi (pid=2547): Exception occurred processing WSGI script '/opt/ada/ada/wsgi.py'. Traceback (most recent call last): File "/opt/ada/venv/lib/python3.8/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'tasks' Also, I can try and call the same task from the shell and it works. The problem only manifests when calling a url that and so must be related to my apache2 site conf file, wsgi.py, or something related What am I missing? -
Django List ID to Form
I apologies if this question has been asked, but I couldnt find anything that could help me solve a small issue. Ive managed to create a django frame work, and created a model and a form containing data from a csv file. Basically what im trying to do is: Ive created a "Home Page", that looks like this(Its just basic to get the idea running): Which contains a list of IDS(With username) from the model/form. what I want to be able to do, is that when i click on one of the id's, for it to open my form page,which relates then to only the data of that ID... I hope that makes sense. So lets say i create a form.html file, and id like it to show all the info in the form/model pertaining to that ID i click on. Maybe it has something to do with Href link? I apologies if im not too clear, but please feel free to ask me anything and il do my best to help These are my files: Model.py: class datas(models.Model): country = models.CharField(_('country'),max_length=200,default='Null') qs_login = models.CharField(_('qs_login'),max_length=200,default='Null') Status = models.CharField(_('Status'),max_length=200,default='Null') seller_id = models.CharField(_('seller_id'),max_length=200,default='Null') Task_ID = models.CharField(_('Task_ID'),max_length=200,default='Null',primary_key=True) associate_queue = models.CharField(_('associate_queue'),max_length=200,default='Null') associate = models.CharField(_('associate'),max_length=200,default='Null') … -
Where can I put user input to Func, and avoid sql injection?
I want to calculate levenstein distance using a custom django function. https://docs.djangoproject.com/en/3.2/ref/models/expressions/#django.db.models.Func lev_dist=Func(F('name'), function='levenshtein', template=f"%(function)s(%(expressions)s, '{symptom.name}')") The problem is that when there is a quote in symptom.name I get an error. The documentation says that you should not put user input into template= because it causes sql injections. If so, where should I put the user input? -
Daphne does not find *server* on production server
I am trying to use django-eventstream to implement SSE events. My code runs perfectly using manage.py runserver on the local PC. However, when I run daphne config.asgi:application on the production server I get the error File "./config/asgi.py", line 21, in <module> url(r'', get_asgi_application()), File "/home/bidforga/virtualenv/bfg/bfg_wag/3.7/lib/python3.7/site-packages/django/core/asgi.py", line 12, in get_asgi_application django.setup(set_prefix=False) File "/home/bidforga/virtualenv/bfg/bfg_wag/3.7/lib/python3.7/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/bidforga/virtualenv/bfg/bfg_wag/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/bidforga/virtualenv/bfg/bfg_wag/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/home/bidforga/virtualenv/bfg/bfg_wag/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/bidforga/virtualenv/bfg/bfg_wag/3.7/lib64/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'server' This is my config/asgi.py import os import django from django.core.asgi import get_asgi_application from django.conf.urls import url from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import django_eventstream os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") application = ProtocolTypeRouter({ 'http': URLRouter([ url(r'^events/', AuthMiddlewareStack( URLRouter(django_eventstream.routing.urlpatterns) ), { 'channels': ['test'] }), url(r'', get_asgi_application()), ]), }) I assume it's looking for server.settings but … -
Problem downloading files in django template
I'm trying to download a file from a local directory in a Django template, but when I click and download it, I get a File Not Found error on my browser. As soon as I click download, the file explorer to choose the folder opens, but when I save the file I get that error. The path to the file I'm sure is right. index.html <a href="path_to_file" download target="_blank">Download</a> -
Request takes too long to Django app deployed in AWS Lambda via Zappa
I have recently deployed a Django backend application to AWS Lambda using Zappa. After the lambda function has not been invoked for some time, the first request to be made takes from 10 to 15 seconds to be processed. At first I thought it would be because of the cold start but even for a cold start this time is unacceptable. Then, reading through Zappa's documentation I saw that it enables by default the keep_warm feature that sends a dummy request to the lambda function every 4 minutes to keep it warm; so this excessive delay in the response to the first request to the lambda is not due to a cold start. Then, I started using tools such as AWS X-Ray and Cloudwatch Insights to try to find the explanation for the delay. Here is what I found out: The invokation that takes a very long time to be processed is the following: Crossed out in red are the names of the environment variables the application uses. They are all defined and assigned a value directly in the AWS Console. What I don't understand is, first of all, why it takes so long, and secondly, why it says the … -
how to name the folder where model images are uploaded
I have model Hotel where is image and name data. class Example(models.Model): image = models.ImageField(upload_to='images', default="images/default.jpg") name = models.CharField(max_length=50) I need to divide the uploaded images into folders that will be named name data in hotel model, as in the case of dating picture = models.ImageField(upload_to='images/%Y/%m/%d/', default="images/default.jpg", blank=True) this picture data is making folder where images are going to be saved. -
what authentication do I choose in discord bot with django rest framework
I have discord quiz bot that is sending questions and collecting data about user and his completed, created, questions. What authentication should I choose? I want only my bot to have access to the api (get, post, put), Token authentication require to have an User model (or no? Im not sure tbh) and I kinda dont want to add it. class UserProfile(models.Model): name = models.CharField(max_length=100) score = models.IntegerField() discord_id = models.IntegerField() attempts = models.IntegerField(default=0) successful_attempts = models.IntegerField(default=0) def __str__(self): return self.name class Meta: ordering = ('-score', ) -
Django-Bootstrap5 form validation error not displaying
I have a form in a modal that needs to be validate. Since Django doesn't do too well with forms in modals and I not rendering the view after the POST but instead using ajax/js to determine the behaviour. I cannot get the invalid-feedback div to show even though I have followed the documentation which states: For invalid fields, ensure that the invalid feedback/error message is associated with the relevant form field using aria-describedby (noting that this attribute allows more than one id to be referenced, in case the field already points to additional form text). Additionally, I can view on the console that the "aria-describedby" attribute is set correctly in the input. index.html <div class="modal-body"> <form class="needs-validation" id="address_form" method="post" novalidate> {% csrf_token %} <div class="mb-3 row"> <label for="id_applicantStreet1" class="col-sm-4 col-form-label">Address Line 1</label> <div class="col-sm-8"> {{form.applicantStreet1}} </div> <div class="invalid-feedback" id="invalid-street1">This is required</div> </div> ..... some more other form fields below index.js $("#address_submit").click(function(){ $.ajax({ type: 'POST', data: $("#address_form").serialize(), url: '/ajax/validate_address_modal', success: function(data){ if(data.status == 200){ window.location.reload(true); } else { responseObj = data.form; for (const key in responseObj){ var id_selector = "#id_"+ key; var message = ""; for (let i = 0; i < responseObj[key].length; i++){ message = responseObj[key][i] + "<br>" + … -
cannot unpack non-iterable ModelBase object in django
i want to view a single in item list with the help of its id but unable to achieve that i am using cbv it is showing me above mention error i am creating a ecommerce website where i want to load only that item detail which he clicking from all the items but unable to achieve showing me above error my models.py class Item(models.Model): categories = models.ForeignKey(Categories, on_delete=models.CASCADE, related_name='our_items') subcategories = models.ForeignKey(Subcategories, on_delete=models.CASCADE, related_name='products') can_buy = models.ForeignKey(For, on_delete=models.CASCADE, related_name='for_wearing') name = models.CharField(max_length=200, blank=False) contain_size = models.CharField(max_length=50, blank=True) brand_name = models.CharField(max_length=100, blank=False, default='Bagh') first = models.ImageField(upload_to='items', blank=False) second = models.ImageField(upload_to='items', blank=False) third = models.ImageField(upload_to='items', blank=True) fourth = models.ImageField(upload_to='items', blank=True) fifth = models.ImageField(upload_to='items', blank=True) item_vedio = models.FileField(upload_to='item_vedio', blank=True) offered_price = models.FloatField(blank=False,) actual_price = models.FloatField(blank=False) about = models.TextField(blank=False, default="about" ) offer = models.CharField(max_length=4, blank=True) def __str__(self): return self.name here is my views.py class Product_detail(View): def get(self, request, products_id): item = Item.objects.get(Item, pk=products_id) category_list = Categories.objects.all() print(item) return render (request, 'products.html',{"item_list" : item, 'category_list': category_list }) my urls.py path('<int:products_id>/details',Product_detail.as_view(),name='detail') my href tag <a href="{% url 'products:detail' products.id %}"> any suggestion will be appreciated thank you for your time -
Django. Create a popup window
In django admin we have popup windows. They do their work when we hit little green plus on some admin pages. For example when we want to create another sample of our model. My question is the following: can I utilize somehow this mechanics in order to create my own popup window when some link or button is hit? Right now a new tab opens. I would like to have a popup window. I saw a boolean option which i can render in the context, which is called is_popup. Maybe i should use it? Unfortunately when i just set it to True right now, it does not toggle a popup window. Just another tab. -
Django : Temporary table or views to create flattened JSON
Can we create a temporary table or views to store the data from 3 or 4 different tables and send a flattened JSON instead of nested JSON to the frontend in Django? My model is: class Place(models.Model): id = models.IntegerField(primary_key=True) location = models.CharField(max_length=100) class Meta: db_table = 'place' managed=False class Session(models.Model): id = models.IntegerField(primary_key=True) place = models.ForeignKey(Place,related_name='session',on_delete=models.CASCADE, null=True) start = models.DateField(auto_now=True) counts = models.IntegerField() class Meta: db_table = 'session' managed=False class Animal(models.Model): id = models.IntegerField(primary_key=True) sess = models.ForeignKey(Session,related_name='details',on_delete=models.CASCADE, null=True) type = models.CharField(max_length=100) is_active = models.BooleanField() length = models.DecimalField(max_digits=6, decimal_places=2) class Meta: db_table = 'animal' managed=False The flatten output I am trying is: [ { "location": "Loc 1", "session_start": "2021-01-01", "session_count": 900, "session_details_id": 1, "session_details_length_max": "22.00", "session_details_length_min": "10.00", "session_details_length_avg": "16.43", "session_details_length_std": "16.00", "session_details_is_active": false, "session_details_type": "dog" }, "location": "Loc 1", "session_start": "2021-01-02", "session_count": 400, "session_details_id": 2, "session_details_length_max": "19.00", "session_details_length_min": "12.00", "session_details_length_avg": "15.43", "session_details_length_std": "13.00", "session_details_is_active": false, "session_details_type": "dog" } ] Instead of nested JSON data that I am currently getting The nested JSON data is [ { "location": "Loc 1", "session": [ { "start": "2021-01-01", "count": 600, "details": [ { "id": 1, "length_max": "15.00", "length_min": "10.00", "length_avg": "12.00", "length_std": "13.00", "is_active": false, "type": "dog" } ] }, { "start": "2021-01-02", "count": … -
Django queryset count total of same foreign key
I'm trying to count and order the total number of the same foreign key for a model. I have two models linked by a foreign key: class CustomerAnalytic(models.Model): product = models.ForeignKey("products.Product", on_delete=models.DO_NOTHING) And I want to know how to get the total number of each foreign key link to this model. For instance: {"product": 1, "customer_analytic_total": 10, "product": 2, "customer_analytic_total": 15,} For now I get the values in a dict and manually do the calculations. I want to optimize this part of the code. I tried to play with aggregate and annotate functions with no success. Is there a way to do it with Django ORM functions?