Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I compare model saved data in django from controller?
I built a django powered webapps,where I used a model field called average CGPA(avg_cgpa) which is a DecimalField in Django model. Also I used a for loop on controller/template to generate all separate data about a student.Now my intention is to compare avg_cgpa data for every row of model to generate a new tag.Where it will be print different result for each student. Like, if avg_cgpa > 2.00 it will be print pass,otherwise fail ! I did tried as you have seen on template but its not working,please come up with your helpfull answer. (Django model here) class Management(models.Model): student_id = models.CharField(max_length=100) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) father_name = models.CharField(max_length=200) mother_name = models.CharField(max_length=200) Present_address = models.TextField(max_length=400) Permanent_address = models.TextField(max_length=400) contact = models.CharField(max_length=11) avg_cgpa = models.DecimalField(max_digits=20,decimal_places=2) def __str__(self): return self.student_id (Here is the template) {% load static %} {% include 'base.html' %} {% block content %} {% include 'navbar.html' %} {% include 'banner.html' %} <div class = "container"> <div class="row"> {% for x in student %} <div class="col-md-4"> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title"><strong>ID : </strong> {{ x.student_id }}</h5> <hr class="my-4"> <img class="card-img-top" src="{% static "images/hat.png" %}"><hr class="my-4"> <h6 class="card-subtitle mb-2 text-muted"><strong><i class="far fa-user-circle"></i> </strong> {{ x.first_name }} … -
Getting more than an object into a template, from a view
I have the following 3 models: class Apartament(models.Model): Nume = models.CharField(max_length=200) Proprietar = models.ForeignKey(User, on_delete=models.CASCADE) Judet = models.CharField(max_length=200) Oras = models.CharField(max_length=200) Strada = models.CharField(max_length=200) pub_date = models.DateTimeField('Data inregistrare') def __str__(self): return self.Nume class Provideri(models.Model): Nume = models.CharField(max_length=200) def __str__(self): return self.Nume class Facturi(models.Model): Numar = models.CharField(max_length=200) Serie = models.CharField(max_length=200) Apartament = models.ForeignKey(Apartament, on_delete=models.CASCADE, default='0') Provider = models.ForeignKey(Provideri, on_delete=models.CASCADE, default='0') Suma = models.DecimalField('Suma de plata', max_digits=5, decimal_places=2) DataEmitere = models.DateField('Data emitere') DataScadenta = models.DateField('Data scadenta') DetaliiFactura = models.TextField('Detalii Factura', help_text="Ce reprezinta factura?") def __str__(self): return "{} - {} {}".format(self.Provider,self.Serie, self.Numar) This view: class DetailView(LoginRequiredMixin, generic.DetailView): model = Apartament template_name = 'apartament/detail.html' And this template: {% extends "base.html" %} {% block content %} {% if apartament.Proprietar == user %} <div class="card"> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <div class="card-header"> {% block title %}{{ apartament.Nume }}{% endblock %} </div> <div class="card-body"> <div class="row"> <div class="col-lg-10"> {{facturi}} {% for factura in facturi %} aaaaaaaaaaa<br> {% endfor %} </div> <div class="col-lg-2"> Judet: {{apartament.Judet}}<br> Oras: {{apartament.Oras}}<br> Strada: {{apartament.Strada}}<br> </div> </div> </div> </div> {% else %} <div class="alert alert-warning" role="alert"> <h4 class="alert-heading">Apartamentul nu iti apartine</h4> <p> Cel putin in aplicatie :) </p> </div> {% endif %} {% endblock %} How can i show on my … -
Retrieve ForeignKey from views before saving in DJANGO
How can i retrieve the foreign key from the form child relationship, save it at the same time that I am saving the parent information on the same page. I am currently working with two forms, the Parent and the child. The logic of the page is saving the name of a book and the name of the course it contains. Ex: Book = "Learn data structure and algorithms", Language = "Python" models.py book_name = models.CharField(max_length=250, blank=False) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users') def __str__(self): return self.book_name def get_absolute_url(self): return reverse('snippets:book_detail', kwargs={'pk': self.pk}) class Language(models.Model): language_name = models.CharField(max_length=12, blank=False) book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='books') def __str__(self): return self.language_name forms.py from django import forms from snippets.models import Book, Language class BookForm(forms.ModelForm): class Meta: model = Book fields = ('book_name',) class LanguageForm(forms.ModelForm): class Meta: model = Language fields = ('language_name',) views.py def create_note(request): if request.method == 'POST': form_one = BookForm(request.POST) form_two = LanguageForm(request.POST) if form_one.is_valid(): book_form = form_one.save(commit=False) book_form.owner = request.user book_form.save() language_form = form_two.save(commit=False) language_form.owner = request.user book_form.save() password_form.save() return redirect('snippets:list') else: form_one = BookForm() form_two = LanguageForm() context = { 'form_one':form_one, 'form_two':form_two, } return render(request, 'snippets/create-note.html', context) I have tried the codes above. The problem is that Django is saving the … -
Create profile at the same time that the user is created
I'm trying to create a profile in the DRF create function in serializer, but when save User model the next exception is triggered ValueError: "<Usuario: Some Name>" needs to have a value for field "id" before this many-to-many relationship can be used. This is my configuration background over python 3 Django == 1.11 DRF == Django rest framework class CustomUserManager(BaseUserManager): def _create_user(self, firstname, lastname, password, **extra_fields): now = timezone.now() if not firstname: raise ValueError(u'The firstname is required.') user = self.model( firstname=firstname, lastname=lastname, last_login=now, **extra_fields ) user.set_password(password) user.save() return user class Usuario( AbstractBaseUser, PermissionsMixin, TimeStampedModel, SoftDeletableModel ): objects = CustomUserManager() class Profile(models.Model): user = models.OneToOneField(Usuario, related_name='profile', on_delete=models.CASCADE) class UserSerializer(serializers.ModelSerializer): profile = PerfilSerializer(read_only=True) def create(self, validate_data): user_data = validate_data profile_data = validate_data.pop('profile') usr = Usuario(**user_data) usr.save() profl = Profile(**profile_data) profl.save() profl.user.set(usr) return usr I want to get the model with the user instance and the profile created -
didn't return an HttpResponse object. It returned None instead
When incorrectly registering a user to my site I get this following error: ValueError at /accounts/register/ The view accounts.views.register didn't return an HttpResponse object. It returned None instead. views.py: def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/accounts') else: form = RegistrationForm() args = {'form': form} return render(request, 'accounts/reg_form.html', args) urls.py: urlpatterns = [ path('', views.home, name="home"), path('explore/', views.explore, name='explore'), path('login/', LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', LogoutView.as_view(template_name='accounts/logout.html'), name='logout'), path('register/', views.register, name='register'), path('profile/', views.view_profile, name='profile'), path('profile/edit/', views.edit_profile, name='profile-edit'), path('change-password/', views.change_password, name='change_password'), path('reset-password/', PasswordResetView.as_view(template_name='accounts/reset_password.html'), name='reset-password'), path('reset-password/done/', PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset-password/confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset-password/complete/', PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] main/urls.py: urlpatterns = [ path('', views.login_redirect, name='login_redirect'), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Advanced forms in django with graphics
How can I use such forms in django as in the picture below? Is there any library that provides it? For simple examples, I am buying a Bootstrap theme, it has everything. <label for="customRange1">Example range</label> <input type="range" class="custom-range" id="customRange1"> How can I now use the easiest way to use Django in my application? -
Query column value of related object and store as variable
I'm trying to grab the value of my column name in my model Category which is linked to my Post model. I want to save the value of name into a variable for later use. I tried print(post.categories.name) but it returns value None. I can confirm that there is an actual value by running post.categories.values() which returns <QuerySet [{'id': 1, 'name': 'General'}]> Model: from django.db import models class Category(models.Model): name = models.CharField(max_length=30) class Post(models.Model): title = models.SlugField(max_length = 250, null = True, blank = True) body = models.TextField() created_on = models.DateTimeField(null=True) last_modified = models.DateTimeField(null=True) categories = models.ManyToManyField('Category', related_name='posts') class Comment(models.Model): author = models.CharField(max_length=60) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) post = models.ForeignKey('Post', on_delete=models.CASCADE) Views: def blog_detail(request, pk): post = Post.objects.select_related().get(pk=pk) category = post.categories.name # This returns None but should return General form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment( author=form.cleaned_data["author"], body=form.cleaned_data["body"], post=post ) comment.save() comments = Comment.objects.filter(post=post) context = { "post": post, "comments": comments, "form": form, } return render(request, "blog_detail.html", context) -
Update list of records and fields into django model with bulk_update
In this question, I was able to store my record using create_bulk in the database. Now I want to update the same list of records in the database. I want to use bulk_update more preferably. my incomplete view is: views.py clean_objects = [Rollcall(is_present=True if 'present' in new_clean_result[key] else False, is_study=True if 'study' in new_clean_result[key] else False, student=User.objects.get(id=int(key)), curriculum_session=session) for key in new_clean_result] if 'add-button' in request.method: Rollcall.objects.bulk_create(clean_objects) session.is_rollcall = True session.save() if ['edit-button'] in post_result: #update records here So, how can I do this? Also I see this link and saw that bulk_update have to argument: 'obj' and 'fields'. What are these arguments? -
How to do this cycle in Django-templates?
How can I make a cycle like this in django for i in arr: for j in arr[i]: pass I tried this: {% for i in arr %} {% for j in arr[i] %} {% endfor %} {% endfor %} -
Using Django signals to identify a present user session
i want to use django signals to identify if a user is logged-in twice and if so, revoke his first session so that only one user session can be present at once. i used the following example but it seems that my signals.py does not even gets reconcnized and i dont know why. Example: How to prevent multiple login in Django accounts/signals.py from django.contrib.auth import user_logged_in from django.dispatch.dispatcher import receiver from django.contrib.sessions.models import Session from .models import UserSession @receiver(user_logged_in) def remove_other_sessions(sender, user, request, **kwargs): # remove other sessions Session.objects.filter(usersession__user=user).delete() # save current session request.session.save() # create a link from the user to the current session (for later removal) UserSession.objects.get_or_create( user=user, session=Session.objects.get(pk=request.session.session_key) ) accounts/models.py # Model to store the list of logged in users class UserSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) session = models.OneToOneField(Session, on_delete=models.CASCADE) accounts/apps.py from django.apps import AppConfig class AccountsConfig(AppConfig): name = 'Accounts' def ready(self): import Accounts.signals but for some reason nothing gets written onto the database for that table. do i maybe miss something here, this is the very first time i get in touch with signals so i might missed something at the configuration. -
Django how to group by multiple fields and sum
I am trying to perform multiple group_by's on my table with the fields same as the serializer below (last column is money) class MoneySerializer(serializers.ModelSerializer): money_sum = serializers.IntegerField() class Meta: model = my_models.Money fields = ('date', 'city', 'money_sum') My Query in my viewset is as follows items = my_models.Money.objects.values('date', 'city').annotate(money_sum=Sum('money')) But with this, I'll have a group_by done for the city column, but I'll still have duplicates for the date field. I would like to group the rows such that it groups by all the same city values and all the same date values. -
Django Emailfield fixed suffix
In my Contact model I use an EmailField to assure I'm saving a valid email address. In my form however, I only want the user to be able to change the part before the @, the domain part is not user defined. (e.g. every email needs to end with @gmail.com) I have looked at a lot of questions about modifying Django form field values before and after validation and display phase, but a lot of the answers are kind of 'hacky' or seem to much of a workaround for my case. Is there some support of kind of a display filter, which manages a fixed prefix/suffix of a Django form field, without having to edit POST values or needing to suppress certain validations? -
Cannot deploy django-channels in production
I am trying to deploy django-channels in production using Gunicorn,Nginx,Postgres and Supervisor.Though i have been able to serve http requests properly but i cannot configure websocket configuration Here is nginx configuration upstream app_server { server unix:/home/datasleek/tracker/run/gunicorn.sock fail_timeout=0; } upstream websocket { server ip-address:80; } server { listen 80; server_name ip-address; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/datasleek/tracker/staticfiles/; } location /media/ { alias /home/datasleek/tracker/media/; } client_max_body_size 4G; access_log /home/datasleek/tracker/logs/nginx-access.log; error_log /home/datasleek/tracker/logs/nginx-error.log; location /ws/ { proxy_pass http://websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location / { proxy_pass http://app_server; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; } } This is supervisor configuration [program:tracker] command=/home/datasleek/trackervenv/bin/gunicorn_start user=datasleek autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/datasleek/tracker/logs/gunicorn.log [program:serverinterface] directory=/home/datasleek/tracker/ command= /home/datasleek/trackervenv/bin/daphne -b 0.0.0.0 -p 80 tracker.asgi:channel_layer autostart=true autorestart=true stopasgroup=true user=datasleek stdout_logfile = /home/datasleek/tracker/logs/daphne.log redirect_stderr=true #[program:tracker_asgi_daphne] #directory=/home/datasleek/tracker/ #command=/home/datasleek/trackervenv/bin/daphne -u /home/datasleek/tracker/daphne.sock --root-path= home/datasleek/tracker tracker.asgi:channel_layer #stdout_logfile = /home/datasleek/tracker/logs/daphne.log [program:tracker_asgi_workers] command=/home/datasleek/trackervenv/bin/python /home/datasleek/tracker/manage.py runworker stdout_logfile = home/datasleek/tracker/logs/worker.log process_name=asgi_worker%(process_num)s numprocs=3 environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 ; Set UTF-8 as default encoding autostart=true autorestart=true redirect_stderr=True stopasgroup=true These are some websocket paths that i am trying to connect ws://ip-address/stream/ And i am getting the following error; ```websocketbridge.js:118 WebSocket connection to 'ws://ip-address/agent-presence/' failed: Error during WebSocket handshake: Unexpected response code: 404``` -
Storing user's IP address in django's database on POST requests
Trying to store user's IP address when he's sending POST requests via submitting my form, tried more than a few suggestions on getting the IP address, but didn't manage to make it work properly as I always get null values stored for the IP in the database table. I tried using model forms and setting the ip address as a variable inside the form so I can store it more easily into the database using request.META.get, and x_forwarded_for to get the actual address from the request in views.py. My app built as below: models.py: class RequestPull(models.Model): a = models.CharField(max_length=10) b = models.CharField(max_length=10) ip_address = models.GenericIPAddressField(null=True)} forms.py: class GetReq(forms.ModelForm): class Meta: model = RequestPull fields = ['a','b','ip_address'] views.py (one of the attempts that give the same result- null values in the database): def get_client_ip(request): remote_address = request.META.get('HTTP_X_FORWARDED_FOR')or request.META.get('REMOTE_ADDR') ip = remote_address x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: proxies = x_forwarded_for.split(',') while (len(proxies) > 0 and proxies[0].startswith(PRIVATE_IPS_PREFIX)): proxies.pop(0) if len(proxies) > 0: ip = proxies[0] print"IP Address",ip return ip def reqPull(request): if request.method == 'GET': form = GetReq() else: form = GetReq(request.POST) if form.is_valid(): form.ip_address = get_client_ip(request) form.save()} expected result is an IP address of the user, as one of the values of … -
How to add social share links to DetailView?
How do I add social sharing feature to my website build in Django. I saw a similar question in SO but that didn't help (below I explained why?), it was asked 6 years ago and I thought probably there must be better ways of doing it after these years. I tried using addthis ,it is elegant and easy to use, but this is the problem when I share a post in Facebook. And also it didn't keep counts number of sharing a post. I also tried other ways either I didn't understand or it didn't work fine. Please help me do this. Thank you very much. -
I want to know if django can dynamically add html tags, just like javascrip
I want to know if django can dynamically add html tags, just like javascrip.if so, how to add html tags dynamically with django-template -
created NULL constraint failed Django 2.2.1
So, first of all, no pending migrations. I get: [...] File "C:\Program Files\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: backup_basenode.created on this line: node = Node(id=old_node.id, name=clean["name"], customer=customer) node.save() The relevant model: class BaseNode(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __str__(self): return f"{str(self.id)}" class Node(BaseNode): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) name = models.CharField(max_length=200) def __str__(self): return f"{self.name}({self.customer})" From what I gather, the created field should be automatically populated and therefore should not be null? As to expected behaviour, I'm trying to elevate a BaseNode to a Node, since I haven't found a direct way of doing it, I went with creating a new Node instance and deleting the BaseNode instance. -
How check response content in view test
I want to check if response objects contain label witch certain value.I have view which add value for certain label if conditions are fulfilled.Of course it works because I checked manually but I want to write test for this. I tried to use assertContain and assertIn, but it doesn't work or I'm using this wrong: class TaskIndexAPI(APITestCase): def setUp(self): user = User.objects.create_user( username='TestUser', password='test1234' ) Task.objects.create( name='Task for test', creator=user, status='Unauthenticated', completion_date=date(2019, 4, 9), description='This is description for test purposes', warning_if_delayed='' ) def test_check_if_delayed(self): response = self.client.get(reverse('tasks_index'), format='json') self.assertContains(response, 'This task is delayed') def test_check_if_delayed(self): response = self.client.get(reverse('tasks_index'), format='json') self.assertIn('This task is delayed', response) This is fragment of view which add value for object label: class UserTasksAPIView(APIView): permission_classes = (permissions.IsAuthenticated,) def get_queryset(self): return Task.objects.filter(creator=self.request.user) def check_if_tasks_are_delayed(self, queryset): checked_tasks = queryset for task in checked_tasks: if task.completion_date <= date.today() and status == 'Unfinished': task.warning_if_delayed = 'This task is delayed' task.save() else: task.warning_if_delayed = '' task.save() return checked_tasks def get(self, request): user_tasks = self.get_queryset() tasks = self.check_if_tasks_are_delayed(user_tasks) serializer = UserTasksSerializer(tasks, many=True) return Response(serializer.data) -
Add a searchbar through class based view
I am new in django and i want to make a searchbar in my web. In my web i display list of form.ModelMultipleChoiceField. And after i add the searchbar in my web, the list is same not change to what i want to search. This is my form in html file : <form method="GET" action="{% url 'diagnosis_penyakit:search' %}"> <p style="margin-left: 700px;">Gejala : </p> <input type="text" name="q" value="{{ request.GET.q }}" id="data" class="form-control" placeholder="Cari gejala disini" style="width: 500px; margin-left: 700px"> <button class="btn btn-success" type="submit" style="margin: 3rem; margin-left: 900px"> Search </button> </form> This is my views.py : def search(request): template = 'penyakit/home.html' query = request.GET.get('q') results = Gejala.objects.filter(Q(gejala__contains=query)) print(results, "search test") if request.user.is_authenticated: form_review = ReviewUserForm(request.POST or None) form = UserResponseForm(request.POST or None) list_rev_user = [] rev_user = ReviewFromUser.objects.all().filter(user_id=request.user.id) for rev in rev_user: list_rev_user.append(rev.number_diagnosis) num_diagnosis = UserAnswer.objects.all().filter(user_id = request.user.id).order_by("-number_diagnosis") num = list_rev_user.count(num_diagnosis[0].number_diagnosis) if len(num_diagnosis)>0: user_answer = UserAnswer.objects.all().filter(user_id = request.user.id, number_diagnosis = num_diagnosis[0].number_diagnosis) diagnosis = DiagnosisPenyakit.objects.all().filter(user_id = request.user.id, number_diagnosis = num_diagnosis[0].number_diagnosis).order_by("-total_point") context = { "form": form, "form_review" : form_review, "user_answer" : user_answer, "diagnosis" : diagnosis, "hasil_diagnosis": diagnosis[0], "num" : num, "query" : query, } return render(request, "penyakit/home.html", context) else: context = { "form": form, } return render(request, "penyakit/home.html", context) else: raise Http404 return render_to_response(request, … -
Send data from javascript to view and return modified data
Now I'm just testing how it works so I use trivial example. I have variable called text in js. I want to send it to view, do some manipulations with it and return it to js. I am managed to send text via ajax POST request but I'm having trouble with understanding how do I return updated value. Here's my script function ajaxTest(){ var text = "text to send"; $.ajax({ url:'test/', type:'POST', data:{text : text, csrfmiddlewaretoken: '{{ csrf_token }}'}, success:function () { console.log("Ajax test success") }, error:function () { console.log("Ajax test failure") } }) } My urlpatterns: from .views import * urlpatterns=[ path('test/', testingAjax), ] And I have view that get this text def testingAjax(request): if request.method == 'POST': x = request.POST.get('text') textToReturn = x + " text to return" return HttpResponse #And here trouble begins elif request.method == 'GET': status = "Nuh uh" return HttpResponse(status) What should I put in HttpResponse and how can I catch this data in javascript now (for console log it for example)? -
Scheduling a task in python that repeats itself hourly and another that repeats itself daily
I am working on a project which stores data from API on hourly as well as a daily basis, am using Django-background-tasks for repetition on an hourly and daily basis. I am not able to figure out how to start the data collection process at a particular time(2:00, 3:00 ......) and than repeat using the regular Django-background-tasks repeat mechanism so as I can later on filter the data from a particularly good time(2:00, 3:00, ..... not 2:15,3:15) to another. So, it would be great if someone points out a specific way to do so. Thanks in advance. -
how to convert date to date drop down and drop down could be separate day, month,year
<p> <label for="id_date_of_birth">Date of birth:</label> <input type="date" name="date_of_birth" value="2019-06-14" id="id_date_of_birth"> </p> i am getting data from database by using django and i am trying to show in drop down date but i am getting date table -
Djagno specify decimal places for FloatRangeField
I have a model which has FloatRangeField class LenderProfile(models.Model): ... interest_range = FloatRangeField('Interest', null=True, blank=True) And I have a model form: class LenderProfileForm(forms.ModelForm): ... interest_range = InclusiveFloatRangeField() Now, I want to specify 2 fixed decimal places (Only in UI, database check is not important) Seems models.FloatRangeField doesn't support decimal_places. And I cant't find any example in django documentation to specify decimal places for FloatRangeField with widgets. -
Add menu in django-simple-menu from context_processors
I don't overcome to solve an issue by using django-simple-menu and context_processors. The idea is to be able to generate menu entries dynamically from a queryset containing request parameter. But I don't get a solution in order to call this context_processors in my html template, especially in the block menu which let to generate tabs. This is my context_processors: def list_of_edition(request): """ Return list of tab editions in navbar menu according to each application :var current_app: get the name of the current application :var instance: list of objects (tabs) displayed for a specific application :var od: dictionnary with application and collections associated thanks to ManyToManyField and related_name :return list_of_tab_edition: list of MenuItem on which one, menu is looping for display tabs in navbar """ current_app = request.cur_app instance = MyModel.objects.filter(application=current_app, display=True).order_by('order') od = OrderedDict() for version in instance: od.setdefault((version.pk, version.title), []).extend([(subversion.pk, subversion.title, subversion.version, subversion.creation_date.year, subversion.code) for subversion in version.collection.all().order_by('-pk')]) list_of_tab_edition = list() for version in od: edition_children = list() for element in od[version]: edition_children.append(MenuItem( f"{element[2].split('.')[0]}th Edition {element[3]} ({element[2]})", reverse('frontend:search', kwargs={'master_code': element[4]}), weight=150, separator=False),) Menu.add_item("edition", MenuItem(version[1], "#edition", children=edition_children)) list_of_tab_edition.append(Menu) print(f"list of tab editions: {list_of_tab_edition}") # print : list of tab editions: [<class 'obj.core.menu.Menu'>, <class 'obj.core.menu.Menu'>] return { 'menu_edition': list_of_tab_edition } In … -
Django ORM annotate on foreign key query
I have 3 models: class Project(models.Model): name = models.CharField(max_length=300, unique=True) description = models.CharField( max_length=2000, blank=True, null=True, default=None ) class QuestionSession(models.Model): name = models.CharField( max_length=500, default=None, null=True, blank=True ) project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='sessions', blank=True, null=True, default=None ) class Question(models.Model): description = models.CharField(max_length=500) question_session = models.ForeignKey( QuestionSession, on_delete=models.CASCADE, related_name='questions', blank=True, null=True, default=None ) As you can see, Project contains Sessions, Session contains questions. What I'm trying to achieve is I wanna fetch a single Project with sessions and number of questions in them. I can do it easily with 2 different queries but I cannot do it in 1 query. My serializers: class SingleProjectSerializer(serializers.ModelSerializer): sessions = MinifiedSessionSerializer(many=True) class Meta: model = Project fields = [ 'id', 'name', 'description', 'sessions' ] class MinifiedSessionSerializer(serializers.ModelSerializer): questions_number = serializers.IntegerField() class Meta: model = QuestionSession fields = [ 'id', 'name', 'questions_number' ] I used to grab sessions in a single query like this: Project.objects.get(id=project_id).sessions.annotate(questions_number=Count('questions')) But how to do it now? I need to fetch the project first and then annotate on sessions. I have no idea how to do it. I need a query like this: Project.objects.filter(pk=project_id).annotate(sessions__questions_number=Count('sessions__questions'))