Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store files inside directory for temporary and make a zip file?
Here I have a list of images that I want to make a zip and download. For this I tried to upload these images inside the project directory first and then trying to zip from this uploaded files. I am getting this error: IOError: [Errno 21] Is a directory: '/home/project/images' How can I send a zip file with these images ? images_list = [image_absolute_url1, image_absolute_url2] folder = os.path.join(BASE_DIR, "images") os.mkdir(folder) with open(folder, 'wb+') as f: for file in images_list: f.write(file) response = HttpResponse(content_type='application/zip') zip_file = zipfile.ZipFile(response, 'w') for filename in images_list: zip_file.write(filename) response['Content-Disposition'] = 'attachment; zip_file' return response -
Django Rest Framework: while using generics APIview I'm not able to set permissions( permissions.py not working for individual users)
I want the admin user to access every user detail and the non-admin user to get access to its own detail only but I'm getting errors while implementing this. As I've shared my views.py, permissions.py, and models.py for the same. I'm not sure whether the problem is in permisions.py or models.py as I'm new to django. I'm using Postman for API testing and this is working fine for the admin user but for an individual user, it's not working. views.py class UserListCreateAPIView(generics.ListCreateAPIView): permission_classes = [IsStaffOrTargetUser] queryset = User.objects.all() serializer_class = UserSerializer class UserRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsStaffOrTargetUser] queryset = User.objects.all() serializer_class = UserSerializer permissions.py class IsStaffOrTargetUser(BasePermission): def has_permission(self, request, view): # allow user to list all users if logged in user is staff return request.user or request.user.is_staff def has_object_permission(self, request, view, obj): # allow logged in user to view own details, allows staff to view all records return request.user.is_staff or obj == request.user models.py class User(AbstractBaseUser): email = models.EmailField(verbose_name='Email',max_length=255,unique=True) name = models.CharField(max_length=200) contact_number= models.IntegerField() gender = models.IntegerField(choices=GENDER_CHOICES) address= models.CharField(max_length=100) state=models.CharField(max_length=100) city=models.CharField(max_length=100) country=models.CharField(max_length=100) pincode= models.IntegerField() dob = models.DateField(null= True) # is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS … -
How do you submit your sitemap with more than one model
I have 6 models in my app, it is necessary to provide all these models in the sitemap.py file, or i will just provided only one models in the sitemap.py file ? . Actually i don't know how this sitemap works, and this is my first time provided this sitemaps to Google search console, will you please shows me how do i submit these models to sitemap in django? my sitemap.py file: from django.contrib.sitemaps import Sitemap from .models import Category class CategorySitemap(Sitemap): def items(self): return Category.objects.all() my models: class Category(models.Model): name = models.CharField(max_length=100, blank=False, null=False) def get_absolute_url(self): return "/p/%i/" % self.id def __str__(self): return str(self.name) class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False) body = RichTextField(blank=False, null=False) category = models.ForeignKey(Category, on_delete=models.CASCADE) slug = models.SlugField(unique=True, max_length=200) def __str__(self): return str(self.title) class Answer(models.Model): user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE) answer = RichTextField(blank=False, null=False) post = models.ForeignKey(Question, blank=False, null=False, on_delete=models.CASCADE) def __str__(self): return str(self.user) class Notification(models.Model): is_read = models.BooleanField(default=False) message = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) url = models.ForeignKey(Answer, on_delete=models.CASCADE) def __str__(self): return str(self.user) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = CloudinaryField('image', blank=True, null=True, default='static/default.jpg') stories = RichTextField(blank=True, null=True) twitter = models.URLField(max_length=300, blank=True, null=True) website = … -
Using expressions inside tags
I'd like to capitalize a string variable and translate it at the same time, but i can't find how to do this in the api docs. i.e. this is throwing an error: {% trans {{ someString | capfirst }} %} -
Django Read Only Fields ,if there is any value
I wrote this code to make read only field, but i want to make an exception that if there is value then that row will only readonly , and if there is not any value the it will be editable, admin.py def get_readonly_fields(self, request, obj=None): if obj: return self.readonly_fields + ("name", "id") return self.readonly_fields -
Django Rest Knox - 403 Forbidden CSRF verification failed
I am using Django Rest Knox for my login/logout views. however, when trying to use these views, I get the following error: Forbidden (403). CSRF verification failed. Request aborted. See an extract of my settings.py below: # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'frontend', 'donations', "authentication", "knox", 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] if PRODUCTION: INSTALLED_APPS.insert(0, "whitenoise.runserver_nostatic") MIDDLEWARE.insert(1, "whitenoise.middleware.WhiteNoiseMiddleware") ROOT_URLCONF = 'system.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'system.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases # Use PostgreSQL in production, otherwise SQLite DATABASES = ( { "default": { "ENGINE": "django.db.backends.postgresql", "HOST": os.environ.get("DB_HOST"), "NAME": os.environ.get("DB_NAME"), "USER": os.environ.get("DB_USER"), "PASSWORD": os.environ.get("DB_PASS"), } } if PRODUCTION else { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } } ) if HEROKU: import dj_database_url db_url = os.environ.get("DATABASE_URL") db_from_env = dj_database_url.config( default=db_url, conn_max_age=500, ssl_require=True ) DATABASES["default"].update(db_from_env) # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Custom user model AUTH_USER_MODEL = "authentication.User" # Django REST framework REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ["knox.auth.TokenAuthentication"], "DEFAULT_PERMISSION_CLASSES": [ … -
django server not starting after configuring the project to run a sass file which I'm using to style my django app
I configured my django app named Eshop in my django project so that I can run the Sass file i have but after restarting the server in the terminal, it's bringing an error "ModuleNotFoundError: No module named 'Eshopcompressor'" I've looked through for the Eshopcompressor but its not there, what next? -
In Django, can I use context in redirect?
I am trying to use redirect with context but I get NoReverseMatch exception. Code snippet is as follows: return redirect(reverse('td:success', kwargs={ 'data': my_data })) However, when I use render, all goes well and I am able to access the context in the template. But I want redirect instead. enter image description here -
Reverse for 'showuser' with keyword arguments '{'bid': 1}' not found. 1 pattern(s) tried: ['showuser/(?P<broadcastid>[0-9]+)\\Z']
I am getting following error: Reverse for 'showuser' with keyword arguments '{'bid': 1}' not found. 1 pattern(s) tried: ['showuser/(?P[0-9]+)\Z'] Does anyone knows how to solve it? urls.py path('showuser/<int:broadcastid>', views.showuser, name="showuser") views.py def showuser(request, broadcastid): vrbrlstnm = BroadcastListSms.objects.get(id=broadcastid) showDepartment = AddContact.objects.values('dept_nm').distinct() if request.method == "GET": if request.GET.get('select') == "All": departmentData = AddContact.objects.all() else: departmentData = AddContact.objects.filter(dept_nm=request.GET.get('select')) return render(request, "showuser.html", {'adduser': vrbrlstnm, 'showDepartment': showDepartment, 'departmentData': departmentData}) return HttpResponseRedirect("showuser", {'showDepartment': showDepartment, 'departmentData': departmentData}) adduser.html <a href="{% url 'showuser' bid=adduser.id %}" class="btn btn-primary"> Add Existing User </a> Note: adduser.id is the foreign key value, from where we get broadcastid. I am stuck here from so many days. Not able to understand what to do now -
How to create authenticated by phone number django
i want to create authenticataion by phone number i don'i know to do it. I don't found any library for django, python. I have authentication by email and password: # models.py class User(AbstractUser): email = models.EmailField(_('email address'), blank=False,unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] How i can create authentication by phone number and verify code which send when user click the button ??? -
Django - Accessing static/media files from a remote url instead of local the one
I cannot find any answer to my question on the web so here it is with some context : I have a Django app running on a server and I would like to continue working on it locally with the "runserver" command. My problem concern the use of common static and media files. The media folder content changing frequently in production I have to download those media files from the server each time I want to dev locally and add those the MEDIA_ROOT path on my computer. The database is common to both dev and production environment since it is a MySQL host on my server. My question is simple, how can I tell Django in local mode to lookup static and media files on a remote url from my domain name instead of localhost ? Searching for media on : https://example.com/media/ instead of : https://127.0.0.1:8000/media/ Hoping this is possible without so much effort ! Thank you in advance for your help -
Refactoring: how to remove a model?
I have a model which is causing too much complexity, and so I want to do away with it and move to a simpler way of doing things. I don't immediately want to scrap the data in this database table, though. class PRSblock( models.Model): PRS = models.ForeignKey( 'jobs.PRS2', models.CASCADE, related_name='prs_blocks') # no other relational fields So, first, migrate the related name prs_blocks to obsolete_prs_blocks and then in the PRS model, add a @property prs_blocks that will assert that it is never called (to trap any bits of code which I failed to remove) Second, rename the model PRSblock to obsolete_PRSblock. IIRC Django makemigrations will ask whether I renamed it, and if I say yes, it will preserve the database table. Does this sound sensible or are there any gotchas I haven't though of? -
How can I add the following JSON to a new URL based on its "category": 2?
I have a JSON array in my server in Django rest framework, but I want to filter them by category , for example some of them have 'category':1 and some of them have 'category':2 like this: [ { "id": 667, "image": "https://ae0g", "description": "GRE", "price": "USD .11", "buy": "https://sn", "category": 1 }, { "image": "https://ae04.", "description": "10/13 ", "price": ".18", "buy": "https://", "category": 2 } ] How can I add the following JSON to a new URL based on its "category": 2? "image": "https://ae04.", "description": "10/13 ", "price": ".18", "buy": "https://", "category": 2 views: class productviewset(viewsets.ModelViewSet): queryset=product.objects.all() serializer_class = productSerializer pagination_class = None def create(self, request): serialized = productSerializer(data=request.data, many=True) if serialized.is_valid(): serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) @action (detail=False , methods=['post']) def delete(self,request): product.objects.all().delete() return Response('success') urls: router = routers.DefaultRouter() router.register(r'product', productviewset,basename='product') # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('api/', include(router.urls)), -
VariableDoesNotExist at
I encountered a problem in django this the problem enter image description here this is my model enter image description here and this is my views.py enter image description here someone could help me? -
Django Template inclusion tags, supress trailing newline
Firstly I know about {% spaceless %}. I don't want to remove all spaces. I just would like the inclusion tag to only render the template, and not add its own trailing '\n' at it's own discretion. E.g. say I have the template tag: from django import template register = template.Library() @register.inclusion_tag(f'myemail/button.html') def myemail_button(href, title, color, background_color): return { 'href': href, 'title': title, 'color': color, 'background_color': background_color, } And this is the inclusion tag's template (myemail/button.html): <table><tbody><tr> <td style="background-color:{{ background_color }}; border-radius:5px; border:solid 1px {{ background_color }}; color:{{ color }}; padding:0px;"> <a href="{{ href }}" style="background-color:{{ background_color }}; border-radius:5px; border:solid 1px {{ background_color }}; color:{{ color }}; display:inline-block; font-weight:bold; padding:12px; text-align:center; text-decoration:none;" target="_blank">&nbsp; {{ title }} &nbsp;</a> </td> </tr></tbody></table> Then when one renders this template (there is no blank line at the start nor end of the file: {% load myemail %}{% myemail_button href="https://example.com" title="CLICK ME!" color="#123456" background_color="#abcdef" %} {% myemail_button href="https://example.com" title="CLICK ME!" color="#123456" background_color="#abcdef" %} It renders as (note the space between the two adjacent <table> elements (this is the new line I would not like auto inserted): <table><tbody><tr> <td style="background-color:#abcdef; border-radius:5px; border:solid 1px #abcdef; color:#123456; padding:0px;"> <a href="https://example.com" style="background-color:#abcdef; border-radius:5px; border:solid 1px #abcdef; color:#123456; display:inline-block; font-weight:bold; padding:12px; … -
Date defaults to Django webserver start date rather than to the default method parameter
I've stumbled on something unexpected, it is probably something basic I'm misunderstanding either in Python or Django. I have a static method in my model class to return the date provided by the user or alternatively return today's date: @staticmethod # By default return today's date or the date provided def get_start_date(**kwargs): startDate = kwargs.get('startDate', datetime.date.today()) return startDate I decided to rewrite it such that the method has the startDate as a default parameter. However, instead of defaulting to today's date it defaults to the date when the Django webserver was first started. Why would this be the case? The method is executed, I've confirmed that the startDate was not provided in the call, even when a variable which I know for certain isn't used anywhere else in the code is entered in the argument, it still returns the date Django was first ran. def get_start_date(startDate=datetime.date.today(), notUsed=datetime.date.today(), **kwargs): print(startDate, notUsed, datetime.date.today()) return startDate >>> 2022-06-23 2022-06-23 2022-06-24 -
Oauth2 - password grant type not working after Django version upgrade to 3.2 LTS
After upgrading my Django app from version 2.2 to 3.2 LTS, the same token generation request that my app was using to generate access and refresh tokens with grant type - password is not working. This is the cURL request I'm using: curl --location --request POST '0.0.0.0:8000/o/token/' \ --header 'Content-Type: application/json' \ --data-raw '{ "grant_type":"password", "username":"xxxx", "password":"xxxx", "client_id":"xxxx", "client_secret":"xxxx" }' I have two docker containers of my app running the same code - one on Django 2.2 and another on Django 3.2. Both are connected to the same postgres db (in a separate container). This same request gives me access and refresh tokens in the Django 2.2 container but in the Django 3.2 container I get this error - { "error": "invalid_grant", "error_description": "Invalid credentials given." } I have checked the documentation of oauth2 toolkit and I'm not seeing any deprecation notes. I moved the django-oauth-toolkit version from 1.2.0 to 1.7.1. Please let me know what I'm missing. -
update data with href link in django and ajax
$("#feedlikes").on("click", function(e){ e.preventDefault(); $.ajax({ type: 'get', url:'{% url "feedlikes" %}', data:{}, success: function({ alert("Updated Successfully") }), }), }), those are my Ajax code help me to get them work. this is my view: def feedlikes(request, feed_id): feed_update= Feeds.objects.get(pk=feed_id) feed_update.likes = feed_update.likes +1 feed_update.save() -
Displaying python list of dictionaries on front-end using django [duplicate]
I have python list as list_dict= [{'_id': ObjectId('6299ba68beb94e0a32af47a8'), 'name': 'Pepperoni', 'size': 'small', 'price': 19, 'quantity': 10, 'date': '2021-03-13T08:14:30Z'}, {'_id': ObjectId('6299ba68beb94e0a32af47a9'), 'name': 'Pepperoni', 'size': 'medium', 'price': 20, 'quantity': 20, 'date': '2021-03-13T09:13:24Z'}, {'_id': ObjectId('6299ba68beb94e0a32af47aa'), 'name': 'Pepperoni', 'size': 'large', 'price': 21, 'quantity': 30, 'date': '2021-03-17T09:22:12Z'}, {'_id': ObjectId('6299ba68beb94e0a32af47ab'), 'name': 'Cheese', 'size': 'small', 'price': 12, 'quantity': 15, 'date': '2021-03-13T11:21:39.736Z'}, {'_id': ObjectId('6299ba68beb94e0a32af47ae'), 'name': 'Vegan', 'size': 'small', 'price': 17, 'quantity': 10, 'date': '2021-01-13T05:08:13Z'}] In template/home.html of my_project in django, I have executed following code: {%block content %} {% for element in list_dict %} <ul> <li>Name:{{element['name']}}</li> <li>Size:{{element['size']}}</li> <li>Price:{{element['price']}}</li> </ul> {% endfor %} {% endblock %} But when i run python manage.py runserver I get error as: Could not parse the remainder: '['name']' from 'element['name']' I'm a beginner in django, kindly looking to learn about my mistakes and fix this error. Thank you. -
Django Authenticate function always returns nine even after making required changes in the settings.py
I am trying to create a login system with Django python. Though the Authenticate function always returns none even after making certain changes in the settings.py as suggested in other StackOverflow answers. I have tried running this code in debug mode in visual studio code and found out the problem lies in the authenticate function only as it's always none and the code hence is never able to log in any user. Here is my code: views.py(login function) from django.http import HttpResponse from django.shortcuts import redirect, render from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib import messages # Create your views here. def home(request): return render(request, 'Home_Page.html') def signup(request): if request.user.is_anonymous: if request.method == 'POST': if User.objects.filter(username=request.POST.get('username').upper()).exists(): messages.error(request, 'The username already exists') elif User.objects.filter(email=request.POST.get('email').lower()).exists(): messages.error(request, 'The Email already exists') else: user = User.objects.create_user(username=request.POST.get('username').upper(), email=request.POST.get('email').lower(), password=request.POST.get( 'password'), first_name=request.POST.get('firstname'), last_name=request.POST.get('lastname')) user.save() return redirect('home') return render(request, 'Signup_Page.html') else: return redirect('/dashboard') def login(request): if request.user.is_anonymous: if request.method == 'POST': user = authenticate(username=request.POST.get( 'username'), password=request.POST.get('password')) if user is not None: login(request, user) return redirect('/dashboard') else: return render(request, 'Login_Page.html') else: return render(request, 'Login_Page.html') else: return redirect('/dashboard') def logout(request): if not request.user.is_anonymous: logout(request) return HttpResponse("Home Page") return redirect('/') Login_Page.html … -
Fetch TOP(N) with Group by Date range for Users using Django ORM
I am trying tio fetch TOP(N) results for every user within a date range. I know to fetch TOP(N) from any model one can use Window and Rank functions like. qs.annotate(rank=Window( expression=Rank(), order_by=F("id").asc(), partition_by=F('user'), ) ).values('id', 'status', 'rank') But I am wondering how to apply Group By for Every User within a Date range. Let me explain with a sample data what I want to achieve I have the following data , You can see from the Following image Alex has 3 entries (id=1,3,7) . But two of them have same dates (3,7) , so out of these two latest entries will be counted i.e., 7. So overall 2 results will returned for User Ales 1 & 7 or Results are returned based on date range filter . If sept 22 filter is applied then only 7 will be returned. Jon has 9 entries (id=6,10,12,15,16,17,18,20,21), For Oct 25 he have 7 entries but l;latest entry id=21 must be returned. So overall, Latest entry for every Used based on dare range must be returned. Date range can be used in filter() if Admin wants to see status counts on specific Dates. -
Fernet Encrypt_key and Decrypt_key both are same but still giving error
I have create an fernet file encryption and decryption using python-cryptography. I can encrypt file but when I decrypt the file with the same key i am getting error for invalid token. Code: ENCRYPTION & DECRYPTION def encrypt_file(blob_name): key = key_gen() fernet = Fernet(key) with open(os.path.join('./static/temp/', blob_name), 'rb') as file: original = file.read() encrypted = fernet.encrypt(original) with open(os.path.join('./static/temp/', blob_name), 'wb') as encrypted_file: encrypted_file.write(encrypted) def decrypt_file(blob_name): print(blob_name) with open('./static/temp/filekey.key', 'rb') as filekey: key = filekey.read() fernet = Fernet(key) with open('./static/temp/'+blob_name, 'rb') as enc_file: print(enc_file) encrypted = enc_file.read() print(encrypted) decrypted = fernet.decrypt(encrypted) print(decrypted) with open(os.path.join('./static/temp/', blob_name), 'wb') as dec_file: dec_file.write(decrypted) Folder Tree: project_folder -static -- temp --- blob_name app.py gcpdata.py Error: Traceback (most recent call last): File "\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 2077, in wsgi_app response = self.full_dispatch_request() File "\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1525, in full_dispatch_request rv = self.handle_user_exception(e) File "\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1523, in full_dispatch_request rv = self.dispatch_request() File "\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1509, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args) File "\PROJECT\app.py", line 47, in download decrypt_file('./static/temp/'+list_blobs(bucket_name)) File "\PROJECT\gcpdata.py", line 117, in decrypt_file decrypted_data = f.decrypt(encrypted_data) File "\AppData\Local\Programs\Python\Python39\lib\site-packages\cryptography\fernet.py", line 88, in decrypt return self._decrypt_data(data, timestamp, time_info) File "\AppData\Local\Programs\Python\Python39\lib\site-packages\cryptography\fernet.py", line 145, in _decrypt_data self._verify_signature(data) File "\AppData\Local\Programs\Python\Python39\lib\site-packages\cryptography\fernet.py", line 129, in _verify_signature raise InvalidToken cryptography.fernet.InvalidToken -
How to run Django Project on HTTPS locally?
Is there a way to run a Django Project on localhost on something like https://localhost/app-name/ on a Windows 10 machine? -
After downloading and opening an excel file it is showing me an error(Django, python)
Here is my view.py code : def downloadfile(request, filename=''): if filename != '': BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = 'SampleExcel.xls' filepath = BASE_DIR + "\SampleExcel\SampleExcel.xls" path = open(filepath, encoding='cp437') mime_type, _ = mimetypes.guess_type(filepath) response = HttpResponse(path, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response else: return HttpResponseRedirect("adduser", {}) File is downloaded properly, but not opening as you can see in below images. -
SQL query group by and join
I have following problem: N+1 queries in SerializerMethodField Queries in Django ORM - https://gist.github.com/dima-dmytruk23/0183014d76ad25f4e2a0ca87ec225a10 As far as I understand, it is unrealistic to implement this using Django ORM. There is an idea to write this in RAW SQL, but I also don’t understand how to make such a query (