Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is there any solution to show data on django website
project in python and java language django website is used data store in database but not show on website and the software used is pycharm I just want to know the solution to show data on website which is store on database I tried alot of query -
Django MigrationAutodetector not detecting changes properly
I'm developing an app that must handle dynamic models creation using Django v. 4.2.6. I was inspired by the great work of Will Hardy looking at his repo dynamic-models, but unfortunately it uses APIs that are no longer valid, as django changed a lot since v.1.2. I was thinking the project in this way: The user creates a Model instance (and as many Field instances as its model needs - each Field has a foreign key to Model). When a Model or a Field instance are saved/deleted the migrations are made and then applied using signals, so the database contains the schemas and the columns needed to store data. I created a dummy app (dynamic_models) and a real app (api_v1) that handle the storage of the data structure. The api_v1.models contains a Field and a Model models. Currently I was exploring the idea of using a customized flow of the makemigrations command and then a customized flow of the migrate command, called by a function called by a post_save signal sent by Model. Here some code I already wrote: api_v1.models.py from dynamic_models.dynamic_models import DynamicModel, makemigrations class FieldType(models.IntegerChoices): CharField = 1 # Requeires max_length TextField = 2 IntegerField = 3 DecimalField … -
How to display actual field with dropdowns instead of showing id?
I have two models and two serializers models: class P4R(models.Model): p4r_id = models.AutoField(primary_key=True) psc_id = models.ForeignKey(BePsc, on_delete=models.CASCADE, verbose_name='PSC Name') vbb_identifier = models.CharField(max_length=100, verbose_name='VBB Identifier') maturity = models.CharField(max_length=100) capex_opex = models.CharField(max_length=100, verbose_name='CAPEX/OPEX') budget_item = models.ForeignKey(BudgetItem, on_delete=models.CASCADE) paying_interest = models.DecimalField(max_digits=10, decimal_places=2) created_by = models.CharField(max_length=100, default='Admin', null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return str(self.vbb_identifier) class P4RChangingFields(models.Model): p4r_variations_id = models.AutoField(primary_key=True) vbb_identifier = models.ForeignKey(P4R, on_delete=models.CASCADE, verbose_name='VBB Identifier') year_now = models.IntegerField(default=2023, verbose_name=f'Year {current_year}') year_1 = models.DecimalField(max_digits=35, decimal_places=25, verbose_name=f'Year {year_1_name}') year_2 = models.DecimalField(max_digits=35, decimal_places=25, verbose_name=f'Year {year_2_name}') year_3 = models.DecimalField(max_digits=35, decimal_places=25, verbose_name=f'Year {year_3_name}') year_4 = models.DecimalField(max_digits=35, decimal_places=25, verbose_name=f'Year {year_4_name}') year_5 = models.DecimalField(max_digits=35, decimal_places=25, verbose_name=f'Year {year_5_name}') created_by = models.CharField(max_length=100, default='Admin', null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Meta: db_table = 'P4R_VARIATIONS' serializers: class P4RSerializer(serializers.ModelSerializer): class Meta: model = P4R fields = '__all__' class P4RChangingFieldsSerializer(serializers.ModelSerializer): vbb_identifier = serializers.CharField(source='vbb_identifier.vbb_identifier') # vbb_identifier = serializers.SlugRelatedField(slug_field='vbb_identifier', read_only=True) class Meta: model = P4RChangingFields fields = '__all__' As you can see, vbb_identifier is the field that connects between the two table. when user create new row using P4R model, they will need to enter vbb_identifier in the form of strings ("ABC123"). the only relationship both table has is vbb_identifier and its one to many. one P4R object may have multiple P4RChangingFields object related to … -
How to log missing template variable, showing location and context in Django?
I am following this tutorial ("With a logging filter that raises exceptions") to catch all invalid variable names in Django templates. myproject/mysite/logging.py: import logging class MissingVariableError(Exception): """ A variable was missing from a template. Used as an alternative to django.template.base.VariableDoesNotExist, because that exception has some meaning within the template engine. """ class MissingVariableErrorFilter(logging.Filter): """ Take log messages from Django for missing template variables and turn them into exceptions. """ ignored_prefixes = ( "admin/", ) def filter(self, record): if record.msg.startswith("Exception while resolving variable "): variable_name, template_name = record.args if not template_name.startswith(self.ignored_prefixes): raise MissingVariableError( f"{variable_name!r} missing in {template_name!r}" ) from None return False myproject/settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { "missing_variable_error": { "()": "www.logging.MissingVariableErrorFilter", }, }, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "root": { "handlers": ["console"], "level": "WARNING", }, "loggers": { "django": { "handlers": ["console"], "level": 'INFO', "propagate": False, }, "django.template": { "level": "DEBUG", "filters": ["missing_variable_error"], }, }, } When I load the main page I get this in the log Traceback (most recent call last): ... File "/install_dir/site/myproject/mysite/logging.py", line 27, in filter raise MissingVariableError( www.logging.MissingVariableError: 'exception_notes' missing in 'unknown' Problem 1: exception_notes does not appear in my site (see note below) Problem 2: this stack trace … -
Superuser active is turned to False, how can I login to my django admin
Superuser active is turned to False, how can I login to my django admin. I mistakenly turned my active to False as a superuser, now I can't login to my django admin. How can I get back superuser as active? I have tried login but couldn't access admin -
Error reversing django migrations with sql_safe_update mode set in MariaDB
I am running into issues when I try to reverse migrate one of the migrations in Django due to sql_safe_update mode is set in MariaDB. The exact sql statement it runs for reverse is: ALTER TABLE `user` DROP COLUMN `pin_code`; And the error that I get from django is: MySQLdb.OperationalError: (1175, 'You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column') Now my database is in inconsistent state because the column has been dropped and failed migration was not rolled back as MySQL DDL statements are not run in transaction. Now even with --fake it shows the same error. Is there a way to tell django to run migrations with sql_safe_update=0 only for duration of migrations? Note that I cannot turn off sql_safe_update globally as DB admins are adamant on not removing it globally. Also it is not entirely clear why DROP column requires a WHERE statement? -
Query sum with distant foreign key relations in Django
Let's say I have models like this: class Product(models.Model): ... class Item(models.Model): product = models.ForeignKey(Product, related_name="items") quantity = models.IntegerField() class Order(models.Model): item = models.ForeignKey(Item, related_name="orders") quantity = models.IntegerField() I now want to get a list of Product annotated with the field total_supply. "Total supply" is defined for each product as: (sum of all of a product's items' quantity) - (sum of quantity on all of the Order objects associated with one of the product's items.) Here is what I have tried: Product.objects.annotate(actual_supply=Sum("items__quantity") - Sum("items__orders__quantity")) I am getting unexpected results. How am I supposed to write such a query? Thank you -
How to define individual service name for each type of Opentelemetry auto instrumentation in a python application?
We are currently using Datadog for monitoring and observability in our application, and we have integrated OpenTelemetry for distributed tracing. We have encountered one main issue Span Separation: Currently, all the spans from our application are being exported to Datadog under a single service. However, we would like to separate them into different services based on the type of instrumentation used (e.g., Django, Elasticsearch, requests, etc.). Manage.py configure_opentelemetry() #Auto Instrumentation of Django, Psycopg2, Pymemcache, Elasticsearch, URLLib3, Requests DjangoInstrumentor().instrument(request_hook=fix_django_req) PymemcacheInstrumentor().instrument() RequestsInstrumentor().instrument() ElasticsearchInstrumentor().instrument() Psycopg2Instrumentor().instrument(enable_commenter=True, commenter_options={}) URLLib3Instrumentor().instrument() configure_opentelemetry method def configure_opentelemetry(): otlp_exporter = OTLPSpanExporter(endpoint=os.getenv("OTEL_COLLECTOR_URL"), insecure=True) # Set the global TracerProvider with the OTLP exporter trace.set_tracer_provider(TracerProvider(resource=Resource.create({SERVICE_NAME: os.getenv("OTEL_SERVICE_NAME"), "env": os.getenv('OTEL_ENV')}))) # Create a BatchSpanProcessor and add the exporter to it span_processor = BatchSpanProcessor(otlp_exporter) trace.get_tracer_provider().add_span_processor(span_processor) tracer = trace.get_tracer(__name__) Collector Config: receivers: otlp: protocols: grpc: http: processors: batch: # batch metrics before sending to reduce API usage send_batch_max_size: 100 send_batch_size: 10 timeout: 10s memory_limiter: # drop metrics if memory usage gets too high check_interval: 1s limit_percentage: 65 spike_limit_percentage: 20 resourcedetection: detectors: [env, gcp] timeout: 2s override: false transform: error_mode: ignore trace_statements: - context: span statements: - set(attributes["resource.name"], name) exporters: datadog: api: site: ${DD_SITE} key: ${DD_API_KEY} extensions: health_check: service: extensions: [health_check] pipelines: traces: receivers: [otlp] processors: [memory_limiter, resourcedetection, … -
Django simple ModelForm not showing on page (I'm using class based-views), what could be the problem?
I'm trying to build a form to use it as a filter for my project search page, but the {{form}} shows nothing. Here is how everything is set up: The model I'm trying to use from models.py class Exemplar(models.Model): class Meta: verbose_name_plural = 'Exemplares' tipoDeExemplar = models.ForeignKey(TipoDeExemplar, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="Tipo De Exemplar") numeroDeRegistro = models.CharField(max_length=255, verbose_name="Número Do Registro") especie = models.ForeignKey(Especie, on_delete=models.CASCADE, null=True) dataDoRegistro = models.DateField(blank=True, null=True, verbose_name="Data Do Registro") estadoDoExemplar = models.CharField(blank=True, null=True, max_length=255, verbose_name="Estado do Exemplar") tipoDeMaterial = models.CharField(blank=True, null=True, max_length=255, verbose_name="Tipo De Material") procedencia = models.CharField(blank=True, null=True, max_length=255, verbose_name="Procedência") remetente = models.CharField(blank=True, null=True, max_length=255, verbose_name="Remetente") armario = models.CharField(blank=True, null=True, max_length=255, verbose_name="Armário") gaveta = models.CharField(blank=True, null=True, max_length=255, verbose_name="Gaveta") complemento = models.CharField(blank=True, null=True, max_length=255, verbose_name="Complemento") amostraDeOrigem = models.CharFie fotoDoExemplar = models.ImageField(null=True, blank=True, upload_to='imagens/', verbose_name="Foto Do Exemplar") slug = models.SlugField(max_length=255, unique=True) def __str__(self): return self.numeroDeRegistro My forms.py file (very short) from django.forms import ModelForm from acervo.models import Exemplar class ExemplarForm(ModelForm): class Meta: model = Exemplar fields = '__all__' My view on views.py (seems to be working since I can open the page) class BuscaView(ListView): model = Exemplar template_name = 'busca.html' form_class = ExemplarForm Piece of the HTML template where I try to use the Django ModelForm <form action="" method="post"> … -
Django When I choose an account from the account tree using the check box
Django When I choose an account from the account tree using the check box, the account and its details are displayed on same template template acc.html template acc1.html view.py models.py -
OAUTH2 Django problems with client_secret
I was updating an old non documented project, database, users, etc.. Suddenly it came a problem, the client_secret_id is not hashed, if I edited in /o/applications then it become hashed. Is there a simple way to hash every client_secret_id other than manually do it one by one, application per application? I found the library, but I don't have any idea where is the salt, or how to include it -
How to get static files to work in Django | Favicon not getting loaded but appears when entering that directory
I'm having trouble trying to get my static files to work, I've already tried different answers for a long time and I'm getting confused what's the problem. I was trying to load my css with debug turned off, but I think its normal for the css not to appear since django doesn't load static files with debug turned off. My problem was when trying to put a favicon into my test website. I also think in the future I'll have complications with JS, etc.. main.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Hello, Django</title> <!-- load staticfiles--> <link rel="stylesheet" href="{% static 'main.css' %}"> <link rel="shortcut icon" href="{% static "favicon.ico" %}}" type="image/png"> </head> <body> </body> </html> urls.py from django.urls import path from f1trackerapp import views from django.contrib.staticfiles.storage import staticfiles_storage from django.views.generic.base import RedirectView urlpatterns = [ path("", views.f1trackerapp, name="f1trackerapp"), path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('favicon.ico'))) ] settings.py (stackoverflow doesn't let me post full settings.py code) ... from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ... # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', … -
How do I make Django add the plural of category as categories instead of categorys
In my Django project I have a category tables however the plural is showing at categorys is there a way to force categories instead? I tried renaming the table but that did not work I also tried manually changing this by changing my model however I receive the same -
HTML does not recognize CSS file - Django
I recently started working on my first python + django project and I'm working on some visual things, but I noticed that the HTML isn't recognizing my CSS file. I follow the documentation about How to manage static files but nothing worked. So, this is my settings.py #app definition INSTALLED_APPS = [ #personalizacao #'grappelli', #Configuraçoes principais 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles' ] #statics configs STATIC_URL = "/static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', # 'django.contrib.staticfiles.finders.AppDirectoriesFinder', #causes verbose duplicate notifications in django 1.9 ) In my HTML I have {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}" /> And I can call the stuff that I have on the static/img folder with no problem So does anyone know what can it be? I don't know where to look anymore -
AWS EC2 Django Requests working from Public ipv4 address, but not Public ipv4 DNS address
Running a django project on an ubuntu 22.04 instance on a new account including a default VPC. Using a custom security group with 3 inbound rules: ipv6(http) on port 80, ipv4(http) on port 80, and ipv4(ssh) on port 22. Outbound rule is the same as default, ipv4(all) on all ports. No key pair was set. Running with gunicorn, nginx, and supervisor. sudo nginx -t shows no issues, supervisor err logs are empty. /var/log/nginx/access.log shows that the api is receiving requests from both sites with no difference in the logs besides codes 200 29 for the successful request from the public ipv4, and codes 404 197 for the failed request from the public ipv4 DNS. It's also worth noting that the public ipv4 DNS serves the default nginx page on the base url while the public ipv4 shows resource not found. There are no relevant errors in /var/log/nginx/error.log. -
Why is Heroku not updating my Django app's code?
I have a Django blog deployed by Heroku, statics served with S3 Bucket. A few days ago I realised that my changes are not shown in the actual code when I inspect it with Chrome's Inspector tool. I pushed them to the git repo and to heroku master. This project is for my thesis, so it would be really important to resolve this problem. Thank you very much to spend your time helping me in advance. This is one of my latest changes: Added a paragraph to a django signup form that the user can view my Privacy Policy before signing up to my blog. I attached the code from PyCharm: {% extends 'default.html' %} {% block content %} <h1>Signup</h1> <form class="site-form" action="/accounts/signup/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Signup"> </form> <!-- Privacy Policy Link --> <p>By signing up, you agree to our <a href="https://www.termsfeed.com/live/d0e2bb42-feca-4abe-8051-afccfe402f6a">Privacy Policy</a>.</p> {% endblock %} The code from the actual website with Google's Inspector tool: <form class="site-form" action="/accounts/signup/" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="1P17fSXi3R2ihBMd17GqUPmx2pIsL4c855BnGwrhTbenlx4sKQea1nJTuCK0Apei"> <label for="id_username">Username:</label><input type="text" name="username" maxlength="150" autofocus="" required="" id="id_username" data-siid="si_input_0"><br><span class="helptext">Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</span> <label for="id_email">Email:</label><input type="email" name="email" required="" id="id_email" data-siid="si_input_1"> <label for="id_password1">Password:</label><input type="password" name="password1" … -
AWS EC2 instance public ipv4 DNS address pointing to private ipv4 address instead of public ipv4 address
Running a django project on an ubuntu 22.04 instance on a new account including a default VPC. Using a custom security group with 3 inbound rules: ipv6(http) on port 80, ipv4(http) on port 80, and ipv4(ssh) on port 22. Outbound rule is the same as default, ipv4(all) on all ports. No key pair was set. Running with gunicorn, nginx, and supervisor. sudo nginx -t shows no issues, supervisor err logs are empty, and accessing the api through the public ipv4 address http://xx.xxx.xx.xxx works properly, serving content when requested, with the base url showing Not Found. Accessing through the private ipv4 address does not respond. The problem is that when accessing through the public ipv4 DNS address, http://ec2-xx-xxx-xx-xxx.us-east-2.compute.amazonaws.com, where the x values match the public ipv4 address, the site only serves the default nginx page. Running nslookup on the DNS address returns the private ipv4 address. Why doesn't the DNS address point to the public ipv4 address? And why does it serve content at all if it points to the private ipv4 address which doesn't respond? Here are the configurations I used for nginx: Changed nginx.conf user to root, and created/linked django.conf in /etc/nginx/sites-available and /etc/nginx/sites-enabled: `server{ listen 80; Server_name [public … -
Onion site not found - Ubuntu 22.04.3 LTS / Unicorn / nginx / ufw / Dango .. on tor
Django web site does not happen to be accessible .. this is the simple demo django website. As this an onion V3, i increased the bucket size torrc HiddenServiceDir /var/lib/tor/hidden_service/ HiddenServicePort 80 127.0.0.1:8080 Django settings ALLOWED_HOSTS = ['localhost', 'hxzr2qtoxsmmoyywkgnp6ehf5afnqxhj7aeh5iw63hyxicxapiokbpyd.onion'] Local tests are ok file /run/gunicorn.sock sudo systemctl status gunicorn curl --unix-socket /run/gunicorn.sock localhost Config Nginx sudo nano /etc/nginx/sites-available/sooshee server { listen 80; server_name hxzr2qtoxsmmoyywkgnp6ehf5afnqxhj7aeh5iw63hyxicxapiokbpyd.onion; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/dj_test; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } cat /etc/nginx/nginx.conf server_names_hash_bucket_size 128; I just changed the bucket size to comply with onion length The only information i find, is this error message below sudo journalctl -u nginx кас 05 19:44:44 dave-MINI-S nginx[27984]: nginx: configuration file /etc/nginx/nginx.conf test failed кас 05 19:44:44 dave-MINI-S systemd[1]: nginx.service: Control process exited, code=exited, status=1/FAILURE кас 05 19:44:44 dave-MINI-S systemd[1]: nginx.service: Failed with result 'exit-code'. кас 05 19:44:44 dave-MINI-S systemd[1]: Failed to start A high performance web server and a reverse proxy server. кас 05 20:25:47 dave-MINI-S systemd[1]: Starting A high performance web server and a reverse proxy server... кас 05 20:25:47 dave-MINI-S nginx[28269]: nginx: [emerg] could not build server_names_hash, you should increase server_names_hash_bucket_size: 64 кас … -
Django cripsy form with a custom template for button
I have a need for a <button> element for my form submit instead of the layout helper Submit() input with Django and django-crispy-form. If I use {{ my_form|crispy }} I'm able to do this. However, with this method all of the other layout elements in the form are ignored. If I switch back to {% crispy my_form %} I get the layout back, but then my custom HTML button is ignored. Is there any way to have a custom HTML submit button while using the Layout helper? Note: If I add the HTML button below the crispy tag the button renders outside of the form, and I cannot iterate through the form fields in the template because my Layout in the Django form is very complex. -
React chat app messages don't have different className
I am making a chat app with django channels and react. I save the messages in state. When a new message is made I want it to have the className of the current user. The problem is that all messages have the className of the user reading them even if they were written from other. For example I am sending messages from 2 different browsers. The one is logged as first and the other as second. If first sends a message it will appear with a className of first. But for second this message will appear with a className of second chatSocket.onmessage = function(e) { if (ran == true) { const data = JSON.parse(e.data); setMessages(old => [...old, <p ref={oneRef} id={currentUser[0]?.username} className={currentUser[0]?.username}>{data.message}</p>]) } } What can I do to solve this. -
Cannot reach Postgres Flexible Server from Web App
I have a Django app to deploy with a pipeline in azure DevOps and deploy To Azure cloud resources. The Django database is a Postgres Flexible Server in the same resource group. Also I have a virtual network resource in the Group. The pipeline install dependencies and then exec the tests from a command in a Makefile. In the tests step the Django app cannot reach the Database server, the name doesn't resolve to an IP, I try with the server Ip and get the same error. I didn't set any firewall rule neither private endpoints -
custom django signal receiver not being called wagtail code
We have a custom receiver connecting to the task_submitted signal in a project app. I have verified that the receiver is added to the dispatcher receivers Locally the receiver is invoked, however when deployed to our staging evnvironment in cloud foundry in a docker container the receiver is not invoked According to a log the self.receivers is None when invoking the dispatcher.send method ? -
how to start ./manage.py runserver faster? Not type it every time, just launch it with ctrl f5
how to start ./manage.py runserver faster? Not type it every time, just launch it with ctrl f5 Not type it every time, just launch it with ctrl f5 how to start ./manage.py runserver faster? Not type it every time, just launch it with ctrl f5 how to start ./manage.py runserver faster? Not type it every time, just launch it with ctrl f5 -
passenger output: /bin/sh: line 0: exec: python: not found
I am trying to run django app I followed https://support.plesk.com/hc/en-us/articles/12377516625559. on Plesk Obsidian Version 18.0.41 Centos when logged in with root or my user python is aliased and responding I tried adding python to any basrc Any idea Thanks in advanced bellow is a detailed of the log level 7 App 174090 output: + '[' -x /usr/bin/id ']' App 174090 output: + '[' -z 10008 ']' App 174090 output: ++ /usr/bin/id -un App 174090 output: + USER=shlomi App 174090 output: + LOGNAME=shlomi App 174090 output: + MAIL=/var/spool/mail/shlomi App 174090 output: + '[' 10008 = 0 ']' App 174090 output: + pathmunge /usr/local/sbin after App 174090 output: + case ":${PATH}:" in App 174090 output: + pathmunge /usr/sbin after App 174090 output: + case ":${PATH}:" in App 174090 output: ++ /usr/bin/hostname App 174090 output: + HOSTNAME=localhost.localdomain App 174090 output: + HISTSIZE=1000 App 174090 output: + '[' '' = ignorespace ']' App 174090 output: + export HISTCONTROL=ignoredups App 174090 output: + HISTCONTROL=ignoredups App 174090 output: + export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE HISTCONTROL App 174090 output: + '[' 10008 -gt 199 ']' App 174090 output: ++ /usr/bin/id -gn App 174090 output: ++ /usr/bin/id -un App 174090 output: + '[' psacln = shlomi … -
Is it normal that Django ORM makes a DB call on every object in a List View?
I'm facing a problem of extra DB calls to retrieve object's data. I have a model: class Post(models.Model): profile = models.ForeignKey(Profile, related_name="posts", on_delete=CASCADE) project = models.ForeignKey(Project, related_name="posts", on_delete=CASCADE) body = models.TextField(verbose_name="Content", max_length=1300) liked_by = models.ManyToManyField(Profile, related_name="post_likes", blank=True) date_published = models.DateTimeField(auto_now_add=True, verbose_name="Date published") date_modified = models.DateTimeField(auto_now=True, verbose_name="Date modified") is_active = models.BooleanField(verbose_name="Active", default=True) tags = TaggableManager(blank=True, related_name="posts") I am calling a View to list all Post objects (currently, there are 4) but getting 4 extra queries to posts_post for each entity. Is that normal behaviour to make an individual DB call on each entity in DB (not related entities but the root entities). My query : all_posts = ( Post.objects .select_related("profile__specialization", "project") .prefetch_related( "tags", Prefetch( "liked_by", queryset=Profile.objects.select_related("specialization").only( "id", "username", "first_name", "last_name", "photo", "specialization" ) ) ) .annotate( comments_count=Count("comments", distinct=True), likes_count=Count("liked_by", distinct=True) ) .defer("body") .order_by("-date_published") ) My query list as per DjDT: