Writing 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 ArticleSelect record whose datetimefield is older, in minutes, than constant value...
I have a Django-based checkout system for an event I run. It has the following models: Game, Checkout.class Game(models.Model): name = models.CharField(max_length=100) playtime =...
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 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 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 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 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 ArticleHow do I integrate Django with FastAPI?
I'm trying to integrate FastAPI with Django ORM to perform async CRUD operations in my application. I want to take advantage of FastAPI's async capabilities while using Django's ORM for database...
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 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 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 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 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 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 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 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 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 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 ArticleCan I aggregate over values(Many-to-Many->val_a, val_b)?
I'm trying to calculate a lookup for items sharing a common related object + a common value. As an informal summary, I want to use some form of:my_queryset.values(my_related_obj,...
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 Article