Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TabularInline and date range overlap constraint
I use the following formset to avoid overlapping date ranges: class OccupancyInlineFormset(BaseInlineFormSet): def clean(self): super().clean() for form in self.forms: conflicts = Occupancy.objects.filter(unit=form.cleaned_data['unit'], begin__lte=form.cleaned_data['end'], end__gte=form.cleaned_data['begin']) if any(conflicts): raise ValidationError(_('Overlapping occupancies!'), code='overlap') This works well in principle, but my current Occupancy instance always needs to have an end date of 9999-12-31. When I change this date in the admin form for the current instance (and add a new instance with an ende date of 9999-12-31), the clean() function will always raise an exception based on the values stored in the database. I do not really see how I could avoid this without changing the offending end date (9999-12-31 → 2023-01-31) first in a different (unconstrained) form, which defeats the purpose of the TabularInline form. Thanks for any help! -
djnago waiting for server response time problem in production
i have a django app that its main purpose is to make an api . it has: api/ url for api that renders data from db test/ url for a test page that only returns HttpResponse("Done") insert/ url for inserting data to db the speed is ok(255 ms) in development but it's sometimes fast (260 ms) and most of the time slow(30-40 s) in production even for loading that test page which only shows a single word. is this problem related to the code or to the hosting provider? note: we use react for frontend and routes are like: mainsite.com/home and we use subdomain like: api.mainsite.com/api or api.mainsite.com/insert for backend -
Fetch request being blocked by cors policy when GET request is sending a specific value
I have a website which is using the Vue.js framework which connects to a django api. The django api has the following settings: MIDDLEWARE = [ .. "corsheaders.middleware.CorsMiddleware", .. ] CORS_ALLOWED_ORIGINS = ["http://localhost:3000", 'http://127.0.0.1:3000'] The following request works fine: fetch("http://127.0.0.1:8000/select?user_sent=1") However this request causes an error: fetch("http://127.0.0.1:8000/select?user_sent=2") The error caused by the second request: Access to fetch at 'http://127.0.0.1:8000/select?user_sent=2' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. The weird thing is that the second request used to work before. I made a change to my django urls and changed the name of the select path but then changed it back to select and now it is no longer working. I tried changing the name of the select path to /sele and when I do that the request will work fine on the new path. However, I would like to know why it is not working on the /select path. -
Initializing firebase database causes error in project bundled with rollup and babel
I have a project where i'm using typescript to extend the Nakama game server. The portion of code i'm dealing with is basically a typescript project that is bundled with rollup and babel before being imported into the game server. I'm having issues using firebase in the project. let firebaseConfig = { apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', appId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', messagingSenderId: 'xxxxxx', projectId: 'xxxxxxx', authDomain: 'xxxxxxxxxxxxxxxxxxxxxxxx', databaseURL: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', storageBucket: 'xxxxxxxxxxxxxxxxxxxxxxxxx', measurementId: 'xxxxxxxx', }; logger.info("after firebase config"); let app = initializeApp(firebaseConfig); logger.info("initialized firebase"); let db = getDatabase(app); logger.info("initialzed database"); let dbRef = ref(db); logger.info("after initialize db ref");` Immediately the line let db = getDatabase(app); is hit, the program runs into the following error: {"level":"info","ts":"2023-01-31T12:43:46.052+0300","caller":"server/runtime_javascript_logger.go:74","msg":"after firebase config","mid":"dbeec043-ed6d-4dab-9b91-92ff54dd41e5"} {"level":"info","ts":"2023-01-31T12:43:46.055+0300","caller":"server/runtime_javascript_logger.go:74","msg":"initialized firebase","mid":"dbeec043-ed6d-4dab-9b91-92ff54dd41e5"} {"level":"error","ts":"2023-01-31T12:43:46.060+0300","caller":"server/runtime_javascript_logger.go:94","msg":"GoError: error creating match: error creating match: TypeError: Cannot add property [DEFAULT], object is not extensible at getImmediate (index.js:2536:13(73))","rpc_id":"create_match"} As you can see, all the lines above the let db = getDatabase(app); run with no issue until this particular line is encountered. I suspected it may be an issue with my rollup and babel config so i tried getting help from firebase's documentation and also nakama's documentation for configuring rollup and babel. But the issue is still present. I don't know what to do next. Here is … -
Getting forbidden error while accessing a directory in using nginx inside docker
I am using Docker version 4.14 to build a Django application and Nginx as a web service. I have two Dockerfiles, one for nginx and one for the Django app, The Django workflow and API serving are fine with nginx, and even static files are served well through nginx. I use Django logging to log the exceptions in the app to a directory named logs, but when I try to access the directory through nginx, I get a 403 Forbidden error. **nginx docker file** FROM nginx:1.21-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d **nginx conf** server { listen 80; include mime.types; types { text/plain log txt; } location / { proxy_pass http://web:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /code/static/; } location /logs { alias /code/logs/; } } \*\*root dockerfile \*\* FROM python:3.10.2-slim-bullseye ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY ./requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . \*\*docker compose \*\* version: "3.9" services: web: build: . ports: \- "8000:8000" command: gunicorn tech_plotz.wsgi:application --bind 0.0.0.0:8000 volumes: \- static_volume:/code/static \- logs_volume:/code/logs expose: \- 8000 depends_on: \- db db: image: postgres:13 volumes: \- postgres_data:/var/lib/postgresql/data/ environment: \- "POSTGRES_HOST_AUTH_METHOD=trust" … -
'Context' object has no attribute 'render_context'
I am running Django==3.2.12 and trying to generate a rendered tewmplate string. The following is the nuts and bolts of it.... I am recieving the error "'Context' object has no attribute 'render_context'" and can not make any sence of it. It used to work fine. I'm using {% load mjml %} which is installed using node_modules with MJML_BACKEND_MODE = "cmd" MJML_EXEC_CMD = "node_modules/.bin/mjml" from django.template import Template, Context template = Template(verbatum) context = Context({}) try: html_template = template.render(context) except Exception as err: html_template = str(err) -
AttributeError at / 'tuple' object has no attribute 'get'
When i started my Django server, it`s not success. Error: AttributeError at / 'tuple' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1.5 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'get' Exception Location: C:\Users\Admin-16.DESKTOP-PDDKOLS\AppData\Local\Programs\Python\Python39\lib\site-packages\django\middleware\clickjacking.py, line 26, in process_response Raised during: weather.views.index Python Executable: C:\Users\Admin-16.DESKTOP-PDDKOLS\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.0 Python Path: ['C:\Users\Admin-16.DESKTOP-PDDKOLS\Desktop\Погода\WeatherApp', 'C:\Users\Admin-16.DESKTOP-PDDKOLS\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\Admin-16.DESKTOP-PDDKOLS\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\Admin-16.DESKTOP-PDDKOLS\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\Admin-16.DESKTOP-PDDKOLS\AppData\Local\Programs\Python\Python39', 'C:\Users\Admin-16.DESKTOP-PDDKOLS\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Tue, 31 Jan 2023 10:09:23 +0000 can be corrected? P.S. my english is bad. I wanted to run a Django server, but he doesn`t -
Django Channels - Websocket connection failed (production)
I decided to add websockets to my project in order to communicate with the database instantly. But at first I decided to just check if websockets will work on production. I made a test version with chat from Django documentation. To my deep regret they only work locally and I tried to figure out what's wrong. But it didn't work for me. The problem is that on localhost websockets work fine, but when I pour them into production, an error occurs. In asgi I tried to replace test.routing with path(...), but it did not change anything. asgi.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import test.routing os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ERA.settings") ERA_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": ERA_asgi_app, "websocket": AuthMiddlewareStack( URLRouter( test.routing.websocket_urlpatterns ) ), }) routing.py from django.urls import re_path from test import consumers websocket_urlpatterns = [ re_path(r'chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ] nginx.conf location /ws/ { proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_http_version 1.1; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_pass http://0.0.0.0:8443; } javascript code const roomName = JSON.parse(document.getElementById('room-name').textContent); if (window.location.protocol === 'https:') { var chatSocket = new WebSocket( 'wss://' + window.location.host + '/chat/' + roomName + '/' … -
Django - Can not join 2 models
Problem: Joining 2 models in Django. Error: Error during template rendering. Direct assignment to the reverse side of a many-to-many set is prohibited. Use entity_id.set() instead. I have read through all the threads on SO. Tried all the suggested solutions, read the Django documentation and think I just must be fundamentally misunderstanding something. Any help would be much appreciated. I have 2 models. Entity and File. An Entity can have multiples Files but each File only has 1 Entity. The primary keys of each table are just auto incrementing integers. Therefore I want to join column entity_id from File with entity_id from Entity. According to the documentation I have set entity_id in File as a ForeignKey. And I have set entity_id as unique in Entity class Entity(models.Model): pk_entity = models.AutoField(primary_key=True) entity_id = models.IntegerField(blank=True, null=True, unique=True) name = models.CharField(blank=True, null=True) class Meta: managed = False db_table = 'entities' class File(models.Model): pk_file = models.AutoField(primary_key=True) filename = models.CharField(blank=True, null=True) entity_id = models.ForeignKey(Entity, on_delete= models.CASCADE, to_field='entity_id') The view is just trying to render this. I have tried using .all() rather than select_related() but no data renders. class TestListView(ListView): queryset = File.objects.select_related() template_name = "operations/files/test_list.html" And this is the html: {% extends "base.html" %} {% … -
AUTH_USER_MODEL refers to model 'account.User' that has not been installed
hello my setting structure is: enter image description here and in base part added: enter image description here enter image description here and its ok in create-users admin-panell and etc but when im calling enter image description here i got: enter image description here please help me i need user model but get error -
I have to add sms.to for sending otp in my django-rest-framework project . I didn't find any python package for that. how can i implement this?
In this project, I have to send opt to the user. I have to use 'sms.to', can someone tell me how I can do this? -
variable inside blocktranslate not shown up when makemessages
I make a simple template like this <button class="btn">{% blocktranslate %}{{ greeting }} Quy!{% endblocktranslate %}</button> with greeting equals hello. I have added the following MIDDLEWARE, and LANGUAGE_CODE = 'vi'. Everything else is left as default. 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', and LANGUAGE_CODE = "vi" TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = 'static/' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' LANGUAGES = [ ('vi', _('Vietnamese')), ('en', _('English')), ] After running django-admin makemessages -l vi, the .po file is created msgid "%(greeting)s Quy!" msgstr "" I added # vi/LC_MESSAGES/django.po msgid "hello" msgstr "chào" or # en/LC_MESSAGES/django.po msgid "hello" msgstr "hi" and then run django-admin compilemessages but "hello" shown up instead of "chào" or "hi". Why I cannot translate the variable -
How can I design a Django Model with existing rows in one of the column?
I have a challenge with designing Django model that has existing rows in one of the column as shown below:- Gaming device in use Gaming Tax on GGR Tax Rate No of shop/places No of slot machines Total Value I have tried to create one Model with column attributes as fields but I don't figure out how to put number of shops/places and number of slot machines in my Model. -
Action to redirect users to URL
Could you tell me how to create an action in the admin site that will redirect users to a certain URL? That is, in the admin site a user chooses this action and finds themselves on Google. def google(modeladmin, request, queryset): """ I myself write some code here to prevent Django from asking users to select an object. """ URL = "https://google.com" ... Here goes the code to redirect the user to URL ... @admin.register(SemanticsCorePhrases) class SemanticsCorePhrasesAdmin(admin.ModelAdmin): actions = [google, ] -
Limit serializer by user
Here is my model serializer: class FoodImagesSerializerGet(serializers.ModelSerializer): current_user = serializers.HiddenField(default=serializers.CurrentUserDefault()) food = serializers.SlugRelatedField( many=False, read_only=False,slug_field='id', queryset=Food.objects.filter(users=current_user) ) Model: class FoodImages(models.Model): food = models.ForeignKey(FoodCourt, related_name='food_images', related_query_name='food_image', on_delete=models.CASCADE, null=True) class Food(models.Model): users = models.ManyToManyField( Profile, related_name='userfoods', related_query_name='userfood', ) I want to limit the serializer by users so only the users of the food can post images . I want to do that Just with the SlugRelatedField -
connection to server at "localhost" (127.0.0.1), port 5432 failed
I am facing this error "OperationalError at /results/ connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (::1), port 5432 failed: Cannot assign requested address Is the server running on that host and accepting TCP/IP connections?" when I try to run a django application that I just deployed in railway.app. What is the problem and how can I fix? When I run the application locally it works well, it is my first time deploying a django application to production and I have no idea how to solve that issue, your help is greatly appreciated. -
What would be the best way to return the result of asynchronous task to Django views?
I am building a Djano app that processes image in a Celery task. A post inside the view method handles the input and triggers the task. Inside the task, I create a model instance based on the processed image. In the same view, I wanted to return a response of the de-serialization of the model instance. What is the best way to throw this response? Should a frontend expect this on another url? How can I signal my app that the model instance is ready to be served? # models.py class Image(models.Model): name = models.CharField(max_length=50, blank=True) ... # tasks.py @shared_task def long_running_function(user, data): image = Image.objects.create() ... return image # ? # views.py class RequestImage(APIView): def post(self, request): ... image = celery_task_example.delay( request.user.id, request.data ) # if image is ready serializer = ImageSerializer(image) return Response(serializer.data) -
URL.createObjectURL() providing url that redirects to 404 in AWS production env
I have a django application deployed on AWS EBS. I have a function that takes a blob and create URL of it so that I can download the pdf file from the site. The function is working perfectly on localhost but in prod environment the created url from URL.createObjectURL() is redirecting to the error page or 404 page. Im using nginx as the reverse proxy. I have checked the blob is valid and the django function is generating the pdf layout correctly. Below is my js code to build the pdf download link function showFile(blob){ var newBlob = new Blob([blob], {type: "application/pdf"}) if (!newBlob) { console.error("Blob object is not valid"); return; } // Create a link pointing to the ObjectURL containing the blob. const data = window.URL.createObjectURL(newBlob); console.log(data) var link = document.createElement('a'); link.href = data; link.open="file.pdf"; link.download = 'Calculation.pdf'; link.click() } the console.log(data) is returning https://<mydomain>/d6527ea6-5c1d-457a-bfb2-2b6aff01ae31 Any idea on how I can make it work in my prod env? Thank you I tried to log the flow and everything is returning correctly. So I am not sure what is the issue -
Django implement installable plugins at runtime
I want to made Django app that allows creation and then installation of plugins, or modules, for it, somewhat like you can do in CMS. Creator of plugin should define models, some configuration settings and handler functions for actions. Plugin will provide only REST api, so no templates required. Plugins must be installed at runtime - creator fills form, attaches archive with code, and plugin gets installed and activated. Unfortunately, my understanding of Django internals is way too low for this task. The most tricky part is runtime installation. There is answer how to install django app at runtime, but it feels hacky. Also, there is lib called django-pluggins, but it works with older version of Django and seems unmaintained. -
Enable support for django tags inside js
i currently have to use django template tags inside js. Example: <script> {% for od in object %} [convertDate("{{ od.date_recorded|date:'Y-m-d' }}"), {{ od.value_recorded }}], {% endfor %} </script> visual studio code shows error, is there a way to enable this support? -
While getting employee duration from joining to date.today() in Django query using F() objects and DurationField(), I am getting negative output
I am writing a query to get duration between 2 date fields. One is from django model (dateField) and other is simply datetime.date.today(). I have used F() objects for model column value to avoid memory usage. def duration(self): emp_duration = Employee.objects.values('empName', 'empJoining').annotate( duration=(datetime.date.today() - F('empJoining')) ) return HttpResponse(emp_duration) Output: {'empName': 'xyz', 'empJoining': datetime.date(2003, 1, 21), 'duration': -20028098.0} {'empName': 'Amna', 'empJoining': datetime.date(2022, 8, 9), 'duration': -20218786.0} {'empName': 'abc', 'empJoining': datetime.date(2022, 7, 17), 'duration': -20218694.0} Have a look at duration field. I dont understand why its in negative. Then I used ExpressionWrapper with outputfield as DurationField(). Since F() objects needs ExpressionWrapper to define outputFields. def duration(self): emp_duration = Employee.objects.values('empName', 'empJoining').annotate( duration=ExpressionWrapper( (datetime.date.today() - F('empJoining')), output_field=DurationField() ) ) return HttpResponse(emp_duration) Output: {'empName': 'xyz', 'empJoining': datetime.date(2003, 1, 21), 'duration': datetime.timedelta(days=-1, seconds=86379, microseconds=971902)} {'empName': 'Amna', 'empJoining': datetime.date(2022, 8, 9), 'duration': datetime.timedelta(days=-1, seconds=86379, microseconds=781214)} {'empName': 'abc', 'empJoining': datetime.date(2022, 7, 17), 'duration': datetime.timedelta(days=-1, seconds=86379, microseconds=781306)} Days difference is same in each row and not the right answer though. The substraction is not correct. What is the issue, if someone can give me better approach or point out what am I missing here, that will be a favor. Thanks -
Getting {"error": "invalid_grant" } in Django OAUTH when trying to generate a token using AUTHORIZATION CODE FLOW
I'm trying to access token using authorization code flow. Following documentation at Django OAuth Here's my code that's making the post request: curl --location --request POST 'http://127.0.0.1:8000/o/token/' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --header 'Cache-Control: no-cache' \ --header 'Accept: application/json' \ --data-urlencode 'client_id=ngta3GGa3jP6Rmv5Tspj97Bk4aiitHgv1EQilCDS' \ --data-urlencode 'client_secret=zLwMyuXg7WCSFwUDYBxFP3QxHh5mF6xM2hBsKyvRbypac5lV7fl2NoFeeDG3afWWxLedA7qtzD2Mvf68qyBra3A4iUXXlDXJO4LvxuZv4UULU6NLWlObpD0ylQSXbwZD' \ --data-urlencode 'code=q4NfBMbyTNbcIQZ4j7SfgMWL898psv' \ --data-urlencode 'redirect_uri=http://localhost:8000/no/callback/' \ --data-urlencode 'code_verifier=b'\''SlJDWEgyRzNYMks0RTVQVDlRVkFaOFdDUkxHV1A3QURMTjNITFdaMTBLU0tWQkkzMUVWVEZFU0k='\''' \ --data-urlencode 'grant_type=authorization_code' I'm expecting to get an access token when I make the post request, but I'm getting this error: { "error": "invalid_grant" } -
How to print errors in console while Object.DoesNotExist
I have 2 files with functions and im trying to show my errors in celery worker console but i have an error: "DETAIL: Key ("GUID")=(#some-guid) already exists." I have try except in the second "create_section" file but for some reason its not working and i got an error in console, how can i handle that? Return or raise wont help me bcs i need code to work after this error Btw: if i just put my create_section code in create_obj file it works fine create_obj.py: for item in response.json(): object_list_json = json.dumps(item) object_list = ObjectListSerializer.parse_raw(object_list_json) section_list = object_list.Sections try: object_list_model = ObjectList.objects.get(GUID=object_list.ObjectGUID) object_list_model.name = object_list.ObjectName create_section(section_list, object_list_model, SectionList) except ObjectList.DoesNotExist as e: print(e) object_list_model = ObjectList.objects.create(GUID=object_list.ObjectGUID, name=object_list.ObjectName) create_section(section_list, object_list_model, SectionList) create_section.py: blank_section_list = [] for section in section_list: try: blank_section_list.append(SectionList.objects.get(GUID=section.SectionGUID)) continue except SectionList.DoesNotExist as error: print(error) SectionList.objects.create(GUID=section.SectionGUID, name=section.SectionName, details=section.DetailedSectionName, object_list=object_list_model) object_list_model.section_list.set(blank_section_list) object_list_model.save() -
How do you conditionally display/hide one of two forms with a live search in Django?
I have two forms: from django import forms from .models import Entity, Quote class EntityForm(forms.ModelForm): class Meta: model = Entity fields = ['name', 'website', 'contact'] class QuoteForm(forms.ModelForm): class Meta: model = Quote fields = ['entity', 'text', 'notes'] Initially on page load only the entity name field is displayed along with the whole quote form. The website and contact fields should not be displayed. The user fills in the entity name field. We do a live search to get all values in the entity model that are similar to help them fill in the form. If no results are returned from their input text, the website and contact fields should now be displayed. The live search functionality is fairly simple to implement, however I'm struggling with the hide/unhide functionality and could use some help. The page initially loads the quote text and I'm not sure why. Similarly, when I fill in the entity field with strings I know that aren't in the database there's no hide/unhide toggle. <form> <label for="entity-name">Entity Name:</label> <input type="text" id="entity-name" name="entity-name" onkeyup="searchEntities()"> <div id="search_results"></div> </form> <form id="quote-form"> <div class="form-group"> <label for="quote-text">Quote Text:</label> <textarea class="form-control" id="quote-text" name="quote-text" rows="3"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <script> function searchEntities() { … -
How to reduce more `SELECT` queries which are already reduced by "prefetch_related()"?
I have Country, State and City models which are chained by foreign keys as shown below: class Country(models.Model): name = models.CharField(max_length=20) class State(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=20) class City(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE) name = models.CharField(max_length=20) Then, I iterate Country and State models with prefetch_related() as shown below: for country_obj in Country.objects.prefetch_related("state_set").all(): for state_obj in country_obj.state_set.all(): print(country_obj, state_obj) Then, 2 SELECT queries are run as shown below. *I use PostgreSQL and these below are the query logs of PostgreSQL and you can see my answer explaining how to enable and disable the query logs on PostgreSQL: Next, I iterate Country, State and City models with prefetch_related() as shown below: for country_obj in Country.objects.prefetch_related("state_set__city_set").all(): for state_obj in country_obj.state_set.all(): for city_obj in state_obj.city_set.all(): print(country_obj, state_obj, city_obj) Then, 3 SELECT queries are run as shown below: Now, can I reduce 3 SELECT queries to 2 SELECT queries or less?