Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django application migration
I have a class Tweet, and I am trying to add User model to it such that user can have many tweets, but a tweet only belongs to a user. class Tweet(models.Model): context = models.TextField(blank=True, null=True) image = models.FileField(upload_to='images/', blank=True, null=True) when I try to migrate i get this error: ValueError: invalid literal for int() with base 10: 'Anonymous' I had a user = models.ForeignKey(User, on_delete=models.CASCADE, default="anonymous") but I removed it and error still presists -
JavaScript is not working in my Django website
I am trying to add auto image slider in my Django website. I referred to this website for the JS and added following code on my setting.py. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["base/templates/"], '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', ], }, }, ] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_DIR = os.path.join(BASE_DIR,"static") STATIC_URL = '/static/' STATICFILES_DIRS = ( [ os.path.join(BASE_DIR, "static"), ] ) My static folder has 2 folders static folder |- css folder - index.css |- js folder - script.js and css works perfectly on web page but JS is not working at all. here is my HTML <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> {% load static %} <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'css/index.css' %}" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="{% static 'js/script.js' %}"></script> JavaScript code and CSS code are same as in the link above. I would appreciate if you could solve this issue.. -
Authenticate LoginView getting django.utils.datastructures.MultiValueDictKeyError:
Django newbie here I have created a new login form but had troubles with the authentication, read the django documentation and now getting a Multivaluedicktkey error. I am stuck. Initially I have used the build it login view but needed to change it now but things did not go the way I wanted them to be. views.py def login_user(request): form = UserLoginForm(request.POST) email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user is not None: if user.is_active: login(request, user) return redirect('profile') else: form = UserLoginForm() context = { "footer": Footer.objects.filter(name="Generic").first(), 'form': form } return render(request, 'member/register.html', context) forms.py class CustomUserCreationForm(forms.ModelForm): error_messages = { 'password_mismatch': _("Şifreler aynı değil"), } email = forms.EmailField(label="E-Posta Adresi") password1 = forms.CharField(label=_("Şifre"), widget=forms.PasswordInput) password2 = forms.CharField(label=_("Tekrar şifre"), widget=forms.PasswordInput, help_text=_("Lütfen aynı şifreyi girin")) class Meta: model = User fields = ['username','email', 'password1', 'password2'] def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def clean_email(self): if User.objects.filter(email=self.cleaned_data['email']).exists(): raise forms.ValidationError("Vermiş olduğunuz mail adresiyle bir kayıt bulunmaktadır.") return self.cleaned_data['email'] def save(self, commit=True): user = super(CustomUserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserLoginForm(forms.ModelForm): email = forms.EmailField(label="E-Posta Adresi") password = forms.CharField(label=_("Şifre"), widget = forms.PasswordInput) class … -
Set radio button initial value if choices come from queryset
I have a form set up as follows. Form class has radio group: class BookForm(ModelForm): class Meta: widgets = { 'book_type': RadioSelect(attrs={'class': 'horizontal-radiogroup'}), } And in init, the choices are set dynamically: self.fields['book_type'].queryset = available_book_types Where available_book_types is a queryset that is filtered based on conditions. I need to dynamically set a value in the radio group as checked in the template. I tried the following: self.fields['book_type'].initial = available_book_types.filter(category='Fiction').first() But it didn't work. Is there a way to achieve this, or do I need to handle this with JavaScript in the frontend? -
Can't process ajax call on my page because Django request.is_ajax returns True when page is intially loaded
I have a page that makes ajax calls, and my view checks if the call is ajax with .is_ajax function. However, when the page is initially loaded (for example if I stop running the server and then restart it) the is_ajax function seems to return True, which causes a MultiValueDictKeyError at /alltext, because the request does not contain the key "alltext", which contains the data from my other ajax call. The page is a e-commerce product page, and the product has different variants (i.e. size and color), and when the user chooses variants from a dropdown menu (i.e. Large, Blue), it makes an ajax call to the backend to retrieve the price of this specific variant from the database. Here is my code: views.py def product_info(request): if request.method == "GET" and not request.is_ajax: # this is supposed to be loaded on page load return render(request, "product_info.html") elif request.is_ajax and request.method == "GET": print(request.is_ajax) '''When a user chooses a product variant on the page, this makes an ajax call to retrieve the price of this combination''' print("request was ajax") combinations = request.GET["alltext"] combinations_list = combinations.split(";") product = Product.objects.all().latest("id") var_names = Variation.objects.filter(product=product) corresponding_values = [] for i in range(len(combinations_list)): # finding this … -
want to upload image in django without usimg ORM
I want to add upload an image in django. But I don't want to use ORM instead Im using the Mysql commands. But the datatype of images is int in django while blob in mysql what should I do? -
Django-rest-framework How to display links to images from three models
There are 3 django models: Basic model describing the job model: class Homework(models.Model): date_to = models.DateField(auto_now=False) date_created = models.DateTimeField(auto_now=True) lesson = models.CharField(max_length=100) group = models.TextField(max_length=10) body_text = models.TextField(default=None, null=True, blank=True) answer_text = models.TextField(default=None, null=True, blank=True) Job photo model: class Body_Images(models.Model): body_homework = models.ForeignKey(Homework, default=None, on_delete=models.CASCADE) body_image = models.ImageField(upload_to='media/homework/body') And the model of the photo of the answers to the task class Answers_Images(models.Model): answer_homework = models.ForeignKey(Homework, default=None, on_delete=models.CASCADE) answer_image = models.ImageField(upload_to='media/homework/answers') There are also three serializers class GetHomeworkSerializer(serializers.ModelSerializer): body_image = GetHomeworkSerializerBodyImages(many=True) answer_image = GetHomeworkSerializerAnswersImages(many=True) class Meta: model = Homework fields = ('date_to', 'date_created', 'lesson', 'group', 'body_text', 'answer_text', 'body_image', 'answer_image') class GetHomeworkSerializerAnswersImages(serializers.ModelSerializer): answer_homework = serializers.RelatedField(source='Homework', read_only=True) class Meta: model = Answers_Images fields = ('answer_homework', 'answer_image',) class GetHomeworkSerializerBodyImages(serializers.ModelSerializer): body_homework = serializers.RelatedField(source='Homework', read_only=True) class Meta: model = Body_Images fields = ('body_homework', 'body_image') I get an error when trying to get data Got AttributeError when attempting to get a value for field body_image on serializer GetHomeworkSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Homework instance. Original exception text was: 'Homework' object has no attribute 'body_image'. How can I get links to images from Body_Images and Answers_Images in one request? -
How to pass a model instance from one function to the next in Django to prevent hitting the database repeatedly
In the below example you can see that get_object_or_404(Ama, uuid=self.kwargs.get('uuid')) is called three times and hits the database three times. How do I call it only once and pass it around? class InitializeAMAUser(ChoSaaSacLoginRequiredMixin, FormView): template_name = 'components/form.html' def get_form(self, form_class=None): ama = get_object_or_404(Ama, uuid=self.kwargs.get('uuid')) return AmaUserInitializationForm(city=ama.city, request=self.request, email=ama.email, phone = ama.phone, **self.get_form_kwargs()) def get_success_url(self): ama = get_object_or_404(Ama, uuid=self.kwargs.get('uuid')) return ama.get_absolute_url() def form_valid(self, form): form.save() messages.add_message(self.request, messages.SUCCESS, 'User created Successfully') Activity(actor=self.request.user, verb='Initialized Ama User Login') return super().form_valid(form) -
django chat server i get not found on the socket
This is the error. :( [14/Nov/2020 14:19:54] "GET /chat/lobby/ HTTP/1.1" 200 1649 Not Found: /ws/chat/lobby/ [14/Nov/2020 14:19:54] "GET /ws/chat/lobby/ HTTP/1.1" 404 2708 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 51974) Traceback (most recent call last): File "/usr/lib/python3.8/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.8/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.8/socketserver.py", line 720, in __init__ self.handle() File "/usr/lib/python3/dist-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/usr/lib/python3/dist-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/lib/python3.8/socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 104] Connection reset by peer ---------------------------------------- i dont know where I got this bug and why do i get it and how to connect the socket in my server import json from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) my routing.py from django.urls import re_path from . import consumer websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumer.ChatConsumer.as_asgi()), ] views.py from django.shortcuts import render def chat(request): return render(request, "chat/chat.html") def room(request, room_name): return render(request, 'chat/room.html', { 'room_name': room_name }) and urls.py from django.urls import path from . import views urlpatterns = [ path("", views.chat, name='index'), path('<str:room_name>/', views.room, name='room'), ] … -
put <elem> values in xml into an array
I have an xquery that returns this example of xml <root> <elem> xd </elem> <elem> lol </elem> <elem> hihi </elem> </root> how do I put the values of the element inside an array? example: x = [xd,lol,hihi] -
SORRY GUYS MAY YOU PLEASE ASSIST WITH THESE FEW ERRORS BELOW:
ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor f or 'User.user_permissions'. *** here is my code It made me stacked for some days without any solutions , please help on how to clear these errors below. username, password, email class Username(models.Model): username = models.CharField(max_length=100) class Password(models.Model): password = models.CharField(max_length=100) class Email(models.Model): email = models.CharField(max_length=100) # home class User(AbstractUser): is_user = models.BooleanField(default=False) is_ceo = models.BooleanField(default=False) is_manager = models.BooleanField(default=False) class Use(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) username = models.ManyToManyField(Username, related_name='uses') password = models.ManyToManyField(Password, related_name='privates') class Ceo(models.Model): ceo = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) username = models.ManyToManyField(Username, related_name='supervises') password = models.ManyToManyField(Password, related_name='protections') email = models.ManyToManyField(Email, related_name='emailing_from') -
FieldError at / Related Field got invalid lookup: is_null
I'm creating a comment api but when i run the server give this error: FieldError at / Related Field got invalid lookup: is_null i don't know how to fix it. i'm creating a nested comment api. this is my code: #serializer class CommentSerializer(serializers.ModelSerializer): loadParent = serializers.SerializerMethodField("loadPrentData") def loadPrentData(self, comment): comments = Comment.objects.filter(parent=comment) comments_ser = CommentSerializer(comments, many=True).data return comments_ser class Meta: model = Comment fields = ['id', 'user', 'product', 'parent', 'body', 'created', 'loadParent'] class ProductSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField("loadProductComments") def loadProductComments(self, _product): _comments = Comment.objects.filter(product=_product, parent__is_null=True) _comments_ser = CommentSerializer(_comments, many=True, read_only=True).data return _comments_ser class Meta: model = Product fields = ['id', 'category', 'name', 'slug', 'image_1', 'image_2', 'image_3', 'image_4', 'image_5', 'description', 'price', 'available', 'created', 'updated', 'comments'] lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } #views: @api_view() def AddComent(request, parent_id=None): parent = request.data.get("parent_id") serializer = CommentSerializer(data=request.data) if serializer.is_valid(): if parent is not None: comment = Comment.objects.create(user=request.user, product=serializer.validated_data['product'], parent_id=serializer.validated_data['parent'], body=serializer.validated_data['body']) else: comment = Comment.objects.create(user=request.user, product=serializer.validated_data['product'], body=serializer.validated_data['body']) comments_ser = CommentSerializer(comment,many=False, read_only=True).data return Response(comments_ser, status=status.HTTP_200_OK) return Response(status=status.HTTP_400_BAD_REQUEST) -
ImportError: cannot import name 'fields' from 'django.db.models.fields'
I got the following error during creation of django serializer. ImportError: cannot import name 'fields' from 'django.db.models.fields' (/home/user_name/anaconda3/lib/python3.7/site-packages/django/db/models/fields/__init__.py) and the serializer.py file is from django.db.models.base import Model from django.db.models.fields import fields, files from rest_framework import serializers from .models import Lead #create serializers for Lead class LeadSerializer(serializers.ModelSerializer): class Meta: model = Lead fields = '__all__' my current django version is 3.0.7. what is wrong in this code ? -
iterating image in dajngo not woking in table row using boostarp Carousel
i am loading images from database to my template the issue is that if i click sliding button of any image any row only sliding happens in the image of first row in table her is my code: HTML <table class="table table-striped table-hover"> <thead> <tr> <th> </th> <th>Room Type</th> <th>Price</th> <th>sleeps</th> <th>Total Rooms</th> <!-- <th>Room Feature</th> --> <th></th> </tr> </thead> <tbody> {% for room in rooms %} <tr> <td> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner" id="ca"> <div class="carousel-item active"> <img class="d-block w-100" src="https://images.unsplash.com/photo-1525253013412-55c1a69a5738?ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80" alt="First slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="https://images.unsplash.com/photo-1525253086316-d0c936c814f8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80" alt="Second slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="https://images.unsplash.com/photo-1524641234638-4c303747c310?ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80" alt="Third slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <!-- <img style="width: 100%;" src="/static/image/{{room.room_image1}}" alt=""> --> </td> <td>{{room.room_type}}</td> <td>{{room.room_price}}</td> <td>{{room.sleeps}}</td> <td>{{room.room_available}}</td> <!-- <td></td> --> <td> <a href="{%url 'room_edit' room.id %}" class="edit"><i class="material-icons" data-toggle="tooltip" title="Edit">&#xE254;</i></a> <a href="{%url 'room_delete' room.id %}" class="delete" onclick="window.mytest('{{room}}')" id="delcheck{{room}}" data-id="{{room.room_name}}"><i class="material-icons" data-toggle="tooltip" title="Delete">&#xE872;</i></a> </td> </tr> {%endfor%} </tbody> </table> this my template table view hear when i click sliding button any row image sliding happens … -
Django annotate whether field is null
I want to annotate a datetime field to know whether it is null. Something like: Table.objects.all().annotate(date_is_null=XXX(YYY)).values(date_is_null, .....) What do I need to replace XXX(YYY) to check if the field is null? (I'm using .values().annotate() later for a Group By, so it must be in annotate first) -
The full request tracing is not complete for micro services via Jaeger UI
Appreciate your support for the below issue as I built my demo as the below steps, I built two microservices one by Django and the another by Go, Django send HTTP request to Go service, Jaeger tool is configured for UI tracing, Django tracing and Go tracing are separated in Jaeger tool and I do not know the reason although I received Django parent trace id in the request header and it is normal to be all Django request tracing including Go tracing as one request tracing in Jaeger, My Git repo: https://github.com/OmarEltamasehy/django-gotracing-example The below is Django code for calling Golang service def second_view(request): res = requests.get("http://localhost:5000/api/trial") ss = SomeModel.objects.create(name="asdasd") # r.set("soso", "mpmp") return HttpResponse('Hello man') from opentelemetry.instrumentation.django import DjangoInstrumentor from opentelemetry.instrumentation.requests import RequestsInstrumentor from opentelemetry.instrumentation.sqlite3 import SQLite3Instrumentor # for using redis from opentelemetry.instrumentation.redis import RedisInstrumentor from opentelemetry.sdk.trace import TracerProvider from opentelemetry import trace # implementing jaeger from opentelemetry.exporter import jaeger from opentelemetry.sdk.trace.export import BatchExportSpanProcessor trace.set_tracer_provider(TracerProvider()) tracer = trace.get_tracer(__name__) # create a JaegerSpanExporter jaeger_exporter = jaeger.JaegerSpanExporter( service_name='kokowawa', # configure agent agent_host_name='localhost', agent_port=6831, # optional: configure also collector # collector_host_name='localhost', # collector_port=14268, # collector_endpoint='/api/traces?format=jaeger.thrift', # collector_protocol='http', # username=xxxx, # optional # password=xxxx, # optional ) # Create a BatchExportSpanProcessor and add … -
Django get information from AJAX and render template
i've a problem with Django when i try to render a template after getting information from AJAX in a datatable. Can you help me? Here is the code: https://nopaste.xyz/?ccbe158548c85b5e#AxwFMud2UafGzzQVV3Gc7TKpzuo5UYxh6i7f675TRjDU I read i cannot use render template after using request from AJAX. -
Django- 404 error when embedding Youtube link via frontend post form
Introduction: Hello, I am new to Python and Django. Started my first blog project that enable users to create their blogs from the frontend. Problems: When I embed a youtube code in the form text area, it will return a 404 (see=image attached). On the other hand, there is no problem doing it via Django admin panel. Error given when youtube link is embedded via front end Here are the files. Views.py from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Category from .forms import PostForm from django.urls import reverse_lazy from django.shortcuts import render class HomeView(ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'home.html' def CategoryListView(request): category_menu_list = Category.objects.all() return render(request, 'category_list.html', {'category_menu_list': category_menu_list}) class PostDetailView(DetailView): model = Post template_name = 'post_detail.html' class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' class AddCategoryView(CreateView): model = Category template_name = 'add_category.html' fields = '__all__' class UpdatePostView(UpdateView): model = Post form_class = PostForm template_name = 'update_post.html' class DeletePostView(DeleteView): model = Post template_name = 'delete_post.html' success_url = reverse_lazy('home') def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats.replace('-', ' ')) return render(request, 'categories.html', {'cats': cats.title().replace('-', ' '), 'category_posts': category_posts}) Urls.py from .views import HomeView, PostDetailView, AddPostView, UpdatePostView, DeletePostView, AddCategoryView, CategoryView, \ CategoryListView from django.urls import … -
How to change the length of a django form field
I have a django form and I want to increase the length of a field html <td class='email_field'><span class='email_field'>{{ signup_form.email }}</span></td> css .email_field{ width: 350px; background-color: blue; } The background is coloured for 350px, but the field remains at the standard width (180px) What is wrong? -
Why can I run multiple django apps on the same ip address and port in debug mode?
I have a question. When I run a django app, he runs it in localhost: 8000. But if I rerun the app, it reruns it in localhost: 8000. Shouldn't it give error as the server (localhost) with that port (8000) is already busy? -
Is there a way to display json results in html in a nice way passed as a context from django view?
I have my django views which returns a json and passing it as context to my html template but unfortunately i can't find a good way loop through all the results in the html template (which uses Bootstrap 4 cdn) in a nice format with their thumbnails. Here is my view from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse from django.template import loader from youtubesearchpython import SearchVideos import urllib.parse import json def index(request): if request.method == 'POST': query = request.POST['video_name'] search = SearchVideos(str(query), offset = 1, mode = "json", max_results = 10) ytresults = search.result() result_dict = json.loads(ytresults) context = { "result" : result_dict, } template_name = "youloader/results.html" return render(request, template_name, context) else: template_name = "youloader/index.html" return render(request, template_name) in my template i tried to pass only the context key so i can make sure the results are returned as expected. and here is the sample of my template {% extends 'youloader/base.html' %} {% block content %} <div style="padding-top: 20px"> {{ result }} </div> {% endblock %} and i have added the sample output -
Read Excel file from Memory in Django
I am trying to read an excel file from memory in django but keep getting the following error: NotImplementedError: formatting_info=True not yet implemented Here's the code: from pyexcel_xls import get_data def processdocument(file): print("file", file) data = get_data(file) return 1 when I am reading the same file from the local storage it works perfectly data = get_data(r"C:\Users\Rahul Sharma\Downloads\Sample PFEP (2).xlsx") I had a workaound solution in mind i.e. to save the uploaded file temporary in django os and then pass its URL to the function. Can I do that? -
Get word from URL or Title django
i want to get data from URL or article Title, for example if word Scorpio is in URL get somethings.. i try this but need full URL how to get this ? ** **{% if b in article.Title %} <h1>irakli</h1> {% endif %}** ** -
Passing zip object to "include" tag
I am trying to use include to embed one child template into parent template. In the parent template, suppose I need to pass variables as following ( as per the documentation here): {% include "table/order_item_modals.html" with item_change_form_list=item_change_form_list %} This works if the variable item_change_form_list is non-object type (such as string, numeric, of normal list, etc). If I want to pass a zip object, the above tag does not work. The reason I want to pass a zip object is because in my child template, I would like to use for loop over multiple lists in parallel, similar to a problem in this thread. Here, my variable item_change_form_list is defined as following in the view: item_change_form_list = zip (list1, list2, list3) Is it possible to pass a zip object in the include tag? Thanks. -
How to build Django queries to get list of data that satisfy many conditions?
I am trying to get a list of user_id by executing such sqlite query. SELECT u.user_id FROM users u WHERE u.role_id IN ( 1, 2 ) AND ( SELECT COUNT( * ) FROM purchases p WHERE p.user_id = u.id ) >= 1 AND ( SELECT tagged.tag_id FROM tagged INNER JOIN ( SELECT polled.answer_id FROM polled WHERE polled.user_id = u.id ) AS a WHERE a.answer_id = tagged.answer_id ) IN ( 1,2 ) How can run that sql using django orm? It's so hard to understand logic querysets like this... Users.objects.annotate(cnt=Count('purchases')).filter(Exists(Polled.objects.filter(user=OuterRef('pk')))).filter(cnt__gt=1).filter(role__in=[1, 2]).values_list('user_id', flat=True) ForeignKeys Relations Image Please help to build correct queries to get list of users that satisfy the conditions. Thanks.