When we should use "db_index=True" in Django?
When we should define db_index=True on a model fields ?I'm trying to optimize the application & I want to learn more about db_index, in which conditions we should use it ?The documentation says...
View ArticleDjango ORM sporadically dies when ran in fastAPI endpoints using gunicorn...
Other related Questions mention using eitherdjango.db's close_old_connections method or looping through the django connections and calling close_if_unusable_or_obsolete on each.I've tried doing this as...
View ArticleHaversine Python Package in Django ORM query
I'm working in a Django App that stores lat and lng for users. I need to find nearby events for users based on their previously-defined radius. For both Users and Events, I store Latitude and Longitude...
View Articlebackward lookup is not working in django 5.x
We are migrating our django app from django==3.2.25 to django==5.1.6. OneToOneField, ManyToManyField are giving errors on revers lookup.Create fresh setup.python -m venv...
View ArticleMethod in Django to display all attributes' values belonging to a created...
Is there a certain method in Django which allows for retrieving/displaying all attributes' values belonging to an object created via Django?In Python shell, I used the following:>>>...
View ArticleUnable to display data from QuerySet in Django templates
I'm trying to implement a simple search for data on a website. If we specify the a tag in the "search_results.html" template, then all the information that is in it is not displayed, but if we remove...
View ArticleWhy is iterating through a large Django QuerySet consuming massive amounts of...
The table in question contains roughly ten million rows.for event in Event.objects.all(): print eventThis causes memory usage to increase steadily to 4 GB or so, at which point the rows print rapidly....
View ArticleDjango query based on through table
I have a 4 models which are Contents, Filters,ContentFilter , Users.a user can view contents.a content can be restricted using Filters so users can't see it.here are the models.class...
View ArticleDjango `bulk_update()` : Update Different Fields for Each Record in a Single...
I have two model instances, rec1 and rec2, but each has different fields updated:rec1 = MyModel(id=1, name="John") # Only 'name' is changed rec2 = MyModel(id=2, age=30) # Only 'age' is changed Now, I...
View ArticleIs django prefetch_related supposed to work with GenericRelation
UPDATE 2022: The original ticked #24272 which I opened 8 years ago about this issue is now closed in favor of #33651, which once implemented will give us a new syntax to do this type of...
View Articlerun one time for Django model calculated property
class Company_Car(models.Model): @property def days_left(self): print("RUNNED PROPERTY") if self.date_valid is not None and self.date_valid >= datetime.datetime.now().date(): return (self.date_valid...
View ArticleDjango ORM, append external field to QuerySet [duplicate]
I have a simple queryset resulting from this:Books.objects.all()Books is related to Authors like this:Class Books: ... author = models.ForeignKey(Authors, on_delete=models.CASCADE)Class Authors: id =...
View ArticleHow to perform a Django "AND" query with a Reverse ForeignKey or...
I found a different result on an "AND" query depending if it was a reverse of forward query.In a FORWARD query you can do this:Model.objects.filter(x=1) &...
View ArticleDjango filter objects which JSONField value contains in another model's...
I'm not sure if the title of this post made you understand the problem but let me explain:I have models:class ItemCategory(models.Model): name = CharField()class Item(models.Model): brand = CharField()...
View ArticleHow to get a moving average (or max) in time period using Django ORM
I am trying to work out if it's possible/practical to use the Django ORM to get the highest value in an arbitrary timebox out of the database.Imagine a restaurant orders ingredients every day, we might...
View ArticleDjango annotate with ExtractMonth and ExtractYear doesnt extract year
I have this model:class KeyAccessLog(models.Model): key = models.ForeignKey( Key, related_name="access_logs", on_delete=models.CASCADE ) path = models.CharField(max_length=255) method =...
View Articleget_or_create returning error that multiple value of objects exist when I...
I am trying to use get_or_create method to see if a record exists. If the record exists do nothing otherwise create it.This model is basically used on the command that is failing class...
View ArticleHow do I write a Django ORM query that returns a match based on an...
If I have, for example:from django.contrib.postgres.fields import JSONFieldclass MyModel(models.Model): data = JSONField()GIVEN a model instance obj1, where data == ['apple', 'banana', 'orange']GIVEN a...
View ArticleDjango Multi-Database ValueError: "Cannot assign Role object: the current...
I'm encountering a ValueError in my Django application when trying to save a User object with a related UserRoleAssociation in the admin interface. The error occurs in a multi-database setup where both...
View ArticleDjango/PostgreSQL: Unique constraint with a dynamic condition like expires_at...
I'm building a secure OTP system in Django. The model looks like this:class OTP(models.Model): MAX_ATTEMPTS = 3 DEFAULT_EXPIRE_IN_MINUTES = 1 class Purposes(models.IntegerChoices): LOGIN = 1, "Login"...
View ArticleHow to dynamically filter with field name, condition and values in Django
I have a requirement, that is from the client side I will get an array of objects which will have field names, filtering conditions and the filtering values like this.Sample array of objects:[...
View ArticleHow to use Django Q objects with ~Q() inside annotate(filter=...) to exclude...
I'm refactoring a legacy Django Job to use annotate with filtered Count aggregations instead of querying each record individually (avoiding the N+1 problem).I want to count the number of related...
View ArticleWhy would someone set primary_key=True on an One to one reationship...
I was watching a video on django-orm and the instructor stated that:We should set primary_key=True to prevent a Model from having duplicate rows in a OneToOne relationship (Ex: Prevent a user from...
View ArticleDjango: Update multiple objects attributes
Is there a more efficient way of do this maybe with F expressions? Some how to reducing hitting the DB?# 1st way hits DB twice per objectdef something(): pks = [4, 2, 1, 3, 0] for i in range(len(pks)):...
View ArticleDjango ORM: Add integer days to a DateField to annotate next_service and...
I am trying to annotate a queryset with next_service = last_service + verification_periodicity_in_days and then filter by that date. I am on Django 5.2.6 with PostgreSQL. last_service is a DateField....
View ArticleSelect distinct values from a table field
I'm struggling getting my head around the Django's ORM. What I want to do is get a list of distinct values within a field on my table .... the equivalent of one of the following:SELECT DISTINCT...
View ArticleDjango prefetch_related and performance optimisation with multiple QuerySets...
Effectively, I have multiple queries within loops that I am just not happy with. I am seeking some expertise with prefetch_related and other Django query construction optimisations.I start with:users =...
View ArticleCap the number of model rows without a race condition
I'm writing a Django app to accept webmentions. New webmentions get placed into a model called "Pending" until the admin runs a verification action on them.Successfully verified rows are then deleted...
View Articlesorting in django admin list by a custom field alphabetically
I have a simple store / product relationship and I want to sort the products depending on the store name alphabetically.models:class Store(models.Model): name = models.CharField("name", max_length =...
View ArticleWriting Django Func() Expression with multiple parameters and specify the order
I'm using Func() Expressions to use this answer and compute the difference between two dates in business days:class BusinessDaysBetween(Func):"""Implementation of a Postgres function to compute the...
View Article