Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to make date fields timezone unaware when querying a Django model to save in Excel file?
I'm querying my model like this: info = Prorrogation.objects.using('test_database').exclude( contractDate__gte=date.today() ).filter( contractDate__gte=data ).order_by('companyName').values() Then I build a DataFrame using pandas and save a report in excel format, but I'm getting the error Excel does not support datetimes with timezones. Please ensure that datetimes are timezone unaware before writing to Excel., is there a way for me to make the date fields timezone unaware when I query the model? -
How do I add a post method for the api view so that posts can be commented on?
I'm building an API using DRF, and as I am a beginner, I can't get my head across this. I'm building an instagram clone using DRF and was able to attach comments and likes to each post object, but I can only attach likes and comments using the admin panel. I can see the total number of likes/comments and the user who added them as JSON Output though. Is there a way to add an add comment_form to the post_detail view? Here's my models.py file from __future__ import unicode_literals import uuid from django.db import models from django.contrib.auth.models import User from django.conf import settings # Create your models here. class Createpost(models.Model): id = models.UUIDField( primary_key = True, default=uuid.uuid4, editable= False, ) author = models.ForeignKey(User , on_delete=models.CASCADE) title = models.CharField(max_length=50) body = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) post_image = models.ImageField(upload_to='images/',blank=True) @property def total_likes(self): return Like.objects.filter(post_id = self.id).count() @property def likes(self): array = [] for like in Like.objects.filter(post_id = self.id): array.append(like.author.username) return array @property def total_comments(self): return Answers.objects.filter(post_id = self.id).count() @property def comments(self): array = [] for comment in Answers.objects.filter(post_id = self.id): c = {} c['body'] = comment.body c['username'] = comment.author.username c['created_at'] = comment.created_at array.append(c) return array def __str__(self): return self.title … -
Django: want to use in admin list_display a property function from my model
I have a model (FeatureFilm) in which I use a "property" function to retrieve a specific person (SUPERVISOR) from another table (StaffInternal) that points to my FeatureFilm table with a ForeignKey. In the template I can call this property and the SUPERVISOR is also shown to me in a list view. Now I want to populate the list view in the admin panel also with this SUPERVISOR column. Here I now do not know how to call the property function. here are my two Model: class StaffIntern(models.Model): HEAD_OF_POSTPRODUCTION = "HP" HEAD_OF_SALES = "HS" SUPERVISOR = "SV" STAFF_INTERN = [ (HEAD_OF_POSTPRODUCTION, "Head of Postproduction"), (HEAD_OF_SALES, "Head of Sales"), (SUPERVISOR, "Postproduction Supervisor"), ] feature_id = models.ForeignKey( FeatureFilm, on_delete=models.CASCADE, null=True, blank=True, ) tv_movie_id = models.ForeignKey( TvMovie, on_delete=models.CASCADE, null=True, blank=True ) staff_role = models.CharField( choices=STAFF_INTERN, max_length=3, blank=True, help_text="Head of Postproduction, Head of Sales, Postproduction Supervisor, Technical Director, Colorist, " "Re-Recording Mixer, Online Editing, VFX Editing, DCP Mastering ", verbose_name="Stab Rolle", ) staff_involved = models.ForeignKey( CustomUser, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Beteiligte Person", ) class FeatureFilm(ProjectBaseModel): class Meta: verbose_name = "Kinofilm" verbose_name_plural = "Kinofilme" ordering = ["title"] @property def production_companies(self): return [ company for company in self.companyinvolved_set.all() if company.company_role == company.PRODUCTION and company.is_production_list # PR = Produktion … -
Django superuser admin
I can't load the admin login screen. have opened a Web browser and went to “/admin/” on local domain http://127.0.0.1:8000/admin/ was supposed to open admin login window. -
django how can I filter all objects out of a query set
How can I filter out all objects of a given queryset? I know I could create some filter that should never be met but is there a more appropriate way of handling this? -
Django Admin - How to prefill add inline forms values sent through the querystring?
I am able to prefill a form using query-string parameters in Django Admin. Let's say I have the following models: class Book(models.Model): id = models.Autofield(primary_key=True) author = models.ForeignKey(Author, on_delete=models.CASCADE) name = models.Charfield(max_length=200) class Author(models.Model): id = models.Autofield(primary_key=True) name = models.Charfield(max_length=200) If I go to /admin/library/author/add/?name=J.+K.+Rowling the author's name will be properly prefilled. However if I add InlineForms like that: class BookInline(StackedInline): model = Book extra = 0 class AuthorAdmin(ModelAdmin): inlines = [BookInline] admin.site.register(Author, AuthorAdmin) I don't seem to be able to prefill books. I tried: /admin/library/author/add/?name=J.+K.+Rowling&books-TOTAL_FORMS=1&books-0-name=Harry+Potter+and+the+Philosopher's+Stone The author form is prefilled, but the first book form is not prefilled. Do you know how one manages that? -
Loading real time data in javascript chart that shows old data too with Django Framework
I have a Django Framework project (Python) and I want to add a real-time chart to my webpage. For that I am using Plotly. In my script in javascript I am generating random numbers and plotting them in the chart. Now, I want to plot specific data (coming from POST requests thanks to Django Rest Framework) so that the user can check that real-time data, together with old data (for example, from yesterday). The thing is that javascript is running in the client side, that means that my chart starts when the user reload the page, so there is no old data to load, he can just check real time one. If he reload the site, the previous data will disappear too. Any idea of how to achieve this? My script is: <script> function rand() { return Math.random(); } var time = new Date(); var data = [{ x: [time], y: [rand()], mode: 'line', line: {color: '#80CAF6'} }] Plotly.plot('chart', data); var cnt = 0; var interval = setInterval(function() { var time = new Date(); var update = { x: [[time]], y: [[rand()]] } Plotly.extendTraces('chart', update, [0]) if(cnt > 100) { Plotly.relayout('chart',{ xaxis: { range: [cnt-100,cnt] } }); } }, 1000); … -
How to connect 2 many to many fields in Django
I have 2 many to many fields in models and i want to connect them to each other i mean if i connect user in Admin Model with Counter Party i cant see that in Counter Party admin How can i do that? When im trying to do that it shows only in 1 model models.py class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='Пользователь') user_counter = models.ManyToManyField('CounterParty', blank=True, verbose_name='Контрагенты пользователя') def __str__(self): return f'{self.user}' class CounterParty(models.Model): GUID = models.UUIDField(default=uuid.uuid4, editable=True, unique=True) name = models.CharField(max_length=150, verbose_name='Наименование') customer = models.BooleanField(default=False, verbose_name='Заказчик') contractor = models.BooleanField(default=False, verbose_name='Подрядчик') counter_user = models.ManyToManyField(User, blank=True, related_name='counter_user', verbose_name='Пользователи контрагента') class Meta: verbose_name = 'Контрагент' verbose_name_plural = 'Контрагенты' def __str__(self): return admin.py from django.contrib import admin from .models import CustomUser, CounterParty, ObjectList, SectionList from authentication.models import User from authentication.admin import UserAdmin class CustomUserInLine(admin.StackedInline): model = CustomUser can_delete = False verbose_name_plural = 'Пользователи' class CustomUserAdmin(UserAdmin): inlines = (CustomUserInLine,) @admin.register(CounterParty) class CounterPartyAdmin(admin.ModelAdmin): pass admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) user admin counter party admin -
How to deal with json response in django from external API
I am currently building a simple dashboard in Django using data from external API like Amazon SP-API. My main question is how do you keep data in models as all the response are in JSON format. Do you store them as JSON Field or serialize all fields into separate columns in SQL Database? I am iterating over 100 accounts using different refresh tokens. Currently created model with separate columns but some of JSON's are nested multiple times and processing and saving them to database is cpu consuming. -
How to prevent multiple queries by inlines in Django admin?
I fought with this all day yesterday, but can't really find a way out. I've got three models where A is related to C through B. The A-admin inlines B which has the FK to C. The admin inlines are causing queries per item which is incredibly slow. Making the offending fields raw_id_only does help (readonly even further), but that is not what I'm trying to do. I read in a few bug tickets, that this intended behaviour, because they don't want to keep the queryset for the choices in memory. But I do want that. Just I'm not sure where to start. I'd like to create a dict of all C (just id and str actually) in the A-admin once and then pass it to each of the inline admins forms instead of it causing another query. How could I pull this off? Here is the ticket that describes the behaviour in detail: https://code.djangoproject.com/ticket/31295 Thank You! -
How to catch all `select2:open` events in the Django 4 admin site?
I just can't seem to catch the select2:open events that should be triggered by Select2 dropdowns used by Django ForeignKey fields with the autocomplete feature enabled. Here is the code I'm currently running to catch those events (I am trying to automatically set the focus to the child search bar whenever a Select2 is open): -- autofocus_select2_searchbars.js /** * Add an event listener to all the select2 widgets on the page so that * when they are opened, the search input is automatically focused. */ function setFocusOnSearchBarsWhenSelect2WidgetsAreOpen() { console.log('setFocusOnSearchBarsWhenSelect2WidgetsAreOpen'); $(document).on('select2:open', () => { console.log('select2:open'); document.querySelector('.select2-container--open .select2-search__field').focus(); }); } $(document).ready(function () { setFocusOnSearchBarsWhenSelect2WidgetsAreOpen(); }); and I am calling this in change_form.html so it gets applied to every change view in the admin: -- myproject/templates/admin/change_form.html {% extends "admin/change_form.html" %} {% load i18n admin_urls static %} {% block admin_change_form_document_ready %} {{ block.super }} <script src="https://code.jquery.com/jquery-3.6.3.slim.min.js" integrity="sha256-ZwqZIVdD3iXNyGHbSYdsmWP//UBokj2FHAxKuSBKDSo=" crossorigin="anonymous"></script> <script> {% include "./shared/autofocus_select2_searchbars.js" %} </script> {% endblock admin_change_form_document_ready %} The problem is that the select2:open event never gets fired. -
How to avoid duplicates when Prefetch m2m related objects with soft deletable models?
I want to get list of accounts with not deleted relations. Models class User(models.Model): accounts = models.ManyToManyField( to='billing.Account', through='custom_auth.UserAccount', through_fields=('user', 'account'), related_name='users', ) deleted = models.DateTimeField( verbose_name=_('Deleted at'), blank=True, null=True, db_index=True ) objects = UserQuerySet.as_manager() class UserAccount(models.Model): user = models.ForeignKey( to='custom_auth.User', on_delete=models.CASCADE) account = models.ForeignKey( to='billing.Account', blank=True, null=True, on_delete=models.CASCADE) deleted = models.DateTimeField( verbose_name=_('Deleted at'), blank=True, null=True, db_index=True ) class Account(models.Model): _users = models.ManyToManyField('custom_auth.User', blank=True) User Manager class UserQuerySet(models.QuerySet): def prefetch_accounts_for_api(self, request): accounts_qs = Account.objects.all() user_account_qs = UserAccount.objects.filter( user=request.user, account_id=OuterRef('pk'), deleted__isnull=True )[:1] accounts_qs = accounts_qs.filter( useraccount=user_account_qs ) return self.prefetch_related(Prefetch( 'accounts', queryset=accounts_qs, to_attr='enabled_accounts' )) The problem is that when there are two rows in useraccount table (1 deleted and 1 not deleted) and i execute the query: User.objects.all().prefetch_accounts_for_api(request) User have duplicate of not deleted account relation in enabled_accounts attribute. How can i get only one actual account in enabled_accounts? Using PostgreSQL and Django 3.1.7 -
typerror at sign,sign() got an unexpected error 'name'
Photo of errorviews.py error is showing on line 40 and raised during homes.views.signurls.py models.pysettings.py sign.htmlFUll sign.html My admin is showing correctly that I have successfully but my sign in details are not able to reach it. I even tried removing name then the error was showing in password.I searched every single possible outcome on overstack to correct the problem.I cant understand what is going on.pls help me I was making a website and i just want details of my signin from website to go to my admin page my admin page is working completey fine i m just not abled to connect then properly -
How can python generate Dorpbox auth tokens after expire?
In my python website, I added dropbox refresh token, App key and Secret key. And in settings.py file I generate access token from these details. Now, my question is that how it will get new auth token after refresh token after expire it . Settings.py loads only one time when build is done and project starts. after expire token, it giving errors. -
how to handle concurrency of bookmark system in django?
I tried to implement bookmark system for product, when users click bookmark button, it will be recorded in his bookmark table, and update bookmark count field in Product Model. However I faced DB Lock when there is too many request at the same time. Also, I realized that when users add or delete bookmark at the same time, there will be concurency issues like, users can not read Product Information or Bookmark count or DB Lock.. How to handle concurrency in my situation? I know the exclusive lock but it will lower the performance.. please help me.. here are my codes class Bookmark(models.Model): _id = models.AutoField(primary_key=True, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bookmark_user') def __str__(self): return str(self.user) class BookmarkItems(models.Model): _id = models.AutoField(primary_key=True, editable=False) user = models.CharField(max_length=255, null=True, blank=True) image = models.CharField(max_length=255, null=True, blank=True) bookmark = models.ForeignKey(Bookmark, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def image_preview(self): if self.image: return mark_safe('<img src="{0}" width="75" height="75" />'.format(self.image)) else: return '(No image)' def __str__(self): return str(self.product) @api_view(['POST']) @permission_classes([IsAuthenticated]) def addBookmark(request): user = request.user user_id = request.data['user'] product_id = request.data['product_id'] image = request.data['image'] product = Product.objects.get(_id=product_id) with transaction.atomic(): bookmark = Bookmark.objects.get_or_create(user=user) Product.objects.filter(_id=product_id).update( bookmark_count = F('bookmark_count') + 1 ) BookmarkItems.objects.create( user = user_id, image = image, bookmark=bookmark[0], … -
PyCharm - Auto-reloading Django dev server after template changes
How to make my PyCharm to reload Django dev server after i make changes in templates? It reloads on save on every other changes but not for template changes. server is starting by docker compose up We are using Django 3.2.16 entrypoint.sh: exec gunicorn app.wsgi:application --config gunicorn.py --reload settings.py [...] 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", "app.context_processors.get_version", "app.context_processors.get_env", ] }, } ] [...] -
Django static files are not found inside docker container
I am building a Django app with Docker. I run the command collectstatic in my entrypoint when database is ready. When I check my container, the /static/ folder is empty. Thus, Nginx cannot load the static files. # settings.py STATIC_URL = '/static/' STATIC_ROOT = '/static/' Here is my docker-compose file version: "3.9" services: db: image: postgis/postgis:14-3.3 container_name: db volumes: - ./data/db:/var/lib/postgresql/data env_file: - prod.env backend: container_name: backend build: dockerfile: ./django/Dockerfile command: gunicorn api.wsgi:application --bind 0.0.0.0:8000 volumes: - static:/usr/src/app/static ports: - "8000:8000" env_file: - prod.env depends_on: - db nginx: container_name: nginx build: dockerfile: ./nginx/Dockerfile volumes: - static:/usr/src/app/static ports: - "80:80" depends_on: - backend restart: always redis: container_name: redis restart: unless-stopped image: redis:alpine expose: - 6379 worker: container_name: worker build: dockerfile: ./django/Dockerfile command: celery -A api worker -l INFO volumes: - static:/usr/src/app/static env_file: - prod.env depends_on: - db - backend - redis volumes: static: My Nginx configuration: upstream api { server backend:8000; } server { listen 80; location / { proxy_pass http://api; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /usr/src/app/static/; } } backend Dockerfile: # syntax=docker/dockerfile:1 FROM python:3 WORKDIR /usr/src/app RUN apt-get update RUN apt-get install -y libgdal-dev gdal-bin netcat ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 COPY /django/requirements.txt … -
I want the number of unread messages to be displayed next to the menu in django admin panel
i need show number unread messages to be displayed next to the menu in django admin panel or show new user added site like this -
boto3 list items of s3 bucket and give path
I need to list all the items in my media/uploads/ folder on my s3 bucket. I've tried several answers from similar questions but was unable to implement the code snippets. I'm confused how to set up the boto3 connection and so far did not get a list. I work with django. In the end I need a list of the latest items. But getting a list of all the items in that folder would already help a lot. Here is my storage system: settings.py STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" AWS_STORAGE_BUCKET_NAME = "feedingcycle" AWS_S3_REGION_NAME = "eu-central-1" AWS_ACCESS_KEY_ID = "xxxx" AWS_SECRET_ACCESS_KEY = "xxxx" AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" import boto3 bucket_name = AWS_STORAGE_BUCKET_NAME def keys(bucket_name, prefix='/', delimiter='/'): prefix = prefix.lstrip(delimiter) bucket = boto3.resource('s3').Bucket(bucket_name) return (_.key for _ in bucket.objects.filter(Prefix=prefix)), print(keys) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" MEDIAFILES_FOLDER = "media" DEFAULT_FILE_STORAGE = "custom_storages.MediaFileStorage" The def keys is not working in there. I also don't get any error messages... Can I set up the whole thing also in my settings or do I have to make a new .py or model for that? Best wishes, Amber -
expected token 'end of statement block', got '='
I am trying to assign value to a dictionary in Jinja2 and its not working properly and showing error. expected token 'end of statement block', got '=' My Code: {% set sequence = ['a1', 'b1']%} {% set dic = {} %} {% for filter in search_result.filters %} {% for seq_key in sequence %} {% if seq_key == filter.key %} {# here i wish to create a dictionary where key= seq_key and value = filter_object#} {% do dic[seq_key]=filter %} {% endif %} {% endfor %} {% endfor %} -
Filter nested serializer model field (exclude particular field)
I am new to Django and I am trying to exclude a model field in nested serializer. modals.py class Blog(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=30) class Comment(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name="comment") comment_bdy = models.CharField(max_length=30) completed = models.BooleanField(default=False) serializers.py class BlogCommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ("id", "comment_body") class BlogSerializer(serializers.ModelSerializer): comment = BlogCommentSerializer(many=True) class Meta: model = ("id", "title", "description", "comment",) I am trying to exclude comment which have completed=True . I have tried many times like :- class BlogCommentSerializer(serializers.ModelSerializer): def to_representation(self, data): data = data.filter(completed=False) return super(BlogCommentSerializer, self).to_representation(data) But It showing AttributeError: 'CommentReply' object has no attribute 'filter' then I tried using class BlogSerializer(serializers.ModelSerializer): def get_comment(self, instance): comment_instance = instance.comment_set.exclude(completed=True) return BlogSerializer(comment_instance , many=True).data It also didn't work. What I am trying to do I am trying to exclude comments which are completed=True Any help would be much Appreciated. -
How can I merge different Db Models into one?
I have an old Django Project, which I started when I was a beginner. So far it worked but, due to some code refactoring I would like to do, I would like to change the original database models. Basically, I originally made many different models, each one for a user type. old models: class CustomUser(AbstractUser): user_type_data = ( ('admin', 'Admin'), ('instructor', 'Instructor'), ('student', 'Student'), ('renter', 'Renter'), ) user_type = models.CharField( max_length=20, choices=user_type_data, default=1) class Admin(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) date_of_birth = models.DateField(null=True, blank=True) fiscal_code = models.CharField(max_length=50, null=True, blank=True) phone = models.CharField(max_length=50, null=True, blank=True) picture = models.ImageField( blank=True, null=True, default='default.png') address = models.CharField(max_length=100, blank=True, null=True) cap = models.CharField(max_length=10, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) province = models.CharField( max_length=100, choices=PROVINCE_CHOICES, blank=True, null=True) country = CountryField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) def __str__(self): return self.user.username class Meta: ordering = ['last_name'] class Instructor(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) date_of_birth = models.DateField(null=True, blank=True) fiscal_code = models.CharField(max_length=50, null=True, blank=True) phone = models.CharField(max_length=50, null=True, blank=True) picture = models.ImageField( blank=True, null=True, default='default.png') address = models.CharField(max_length=100, null=True, blank=True) cap = models.CharField(max_length=10, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) province = models.CharField( max_length=100, … -
How to upload a file on click of a button in Django?
I have a requirement to upload a zip file on click of an upload/save button. Then when the user clicks on run button the uploaded file should get processed. I have created a basic form and could write code for uploading a file on click of submit as shown in below if request.method=='POST': upload_request=UploadFile() upload_request.file=request.FILES['file_upload'] upload_request.save() Template: <form method="post" enctype="multipart/form-data"> {% csrf_token%} <input type="file" required name="file_upload" id="choose_upload_file" value="" accept=".zip,.rar,.7z,.gz,"></br> <input type="submit" class="btn btn-secondary btn-block" value="upload" id="file_upload1"> </form> But How to have a save functionality (File should be uploaded) before submitting the form? I am new to Django, Please give me some insights. -
how to create a qr-code an sone of one of the fields based on the other when creating an object?
I want to creato objects through admin-pannel Django, I enter a value for a parameter and I want a qr code to be generated based on this value, my code: class People(models.Model): name = models.CharField(max_length=500, unique=True) qr_code = models.ImageField(upload_to="img/qr_codes/", verbose_name="QR-code", null = True) def save(self, *args, **kwargs): qr = qrcode.QRCode(version=2, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=1) qr.add_data(self.name) qr.make(fit=True) qr.make_image().save(f'img/qr_codes/{self.name}.png' self.qr_code = self.name+'.png' super().save(*args, **kwargs) This code return error [Errno 2] No such file or directory: 'img/qr_codes/somename.png' Im trying to use signal @receive but it isn't help for me -
How to use "Prefetch()" with "filter()" to reduce `SELECT` queries to iterate 3 or more models?
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, when I iterate Country, State and City models with prefetch_related() and all() as shown below: # Here # Here for country_obj in Country.objects.prefetch_related("state_set__city_set").all(): for state_obj in country_obj.state_set.all(): # Here for city_obj in state_obj.city_set.all(): # Here print(country_obj, state_obj, city_obj) Then, 3 SELECT queries are run as shown below. *I use PostgreSQL and these below are the query logs of PostgreSQL and you can see this answer explaining how to enable and disable the query logs on PostgreSQL: But, when I iterate with filter() instead of all() as shown below: # Here for country_obj in Country.objects.prefetch_related("state_set__city_set").filter(): for state_obj in country_obj.state_set.filter(): # Here for city_obj in state_obj.city_set.filter(): # Here print(country_obj, state_obj, city_obj) Then, 8 SELECT queries are run as shown below instead of 3 SELECT queries: So, I use Prefetch() with filter() to reduce 8 SELECT queries to 3 SELECT queries as shown below: for obj in Country.objects.prefetch_related( Prefetch('state_set__city_set', # Here queryset=State.objects.filter(), to_attr='result' ), ).filter(): print(obj.result) But, the error below occurs: django.core.exceptions.FieldError: Cannot …