4,075 questions
0
votes
0
answers
70
views
Django ORM: Add integer days to a DateField to annotate next_service and filter it (PostgreSQL)
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. ...
1
vote
1
answer
46
views
How to use Django Q objects with ~Q() inside annotate(filter=...) to exclude a value?
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 ...
3
votes
1
answer
78
views
Django/PostgreSQL: Unique constraint with a dynamic condition like expires_at > now()
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):
...
0
votes
1
answer
42
views
Django Multi-Database ValueError: "Cannot assign Role object: the current database router prevents this relation"
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 ...
2
votes
1
answer
95
views
How do I write a Django ORM query that returns a match based on an intersection of lists?
If I have, for example:
from django.contrib.postgres.fields import JSONField
class MyModel(models.Model):
data = JSONField()
GIVEN a model instance obj1, where data == ['apple', 'banana', '...
1
vote
1
answer
60
views
Django 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(...
-3
votes
1
answer
83
views
How 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 ...
0
votes
0
answers
44
views
Django filter objects which JSONField value contains in another model's JSONField values LIST of same "key"
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 =...
0
votes
1
answer
35
views
Django 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 ...
-1
votes
1
answer
45
views
run 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....
1
vote
3
answers
120
views
Django `bulk_update()` : Update Different Fields for Each Record in a Single Query
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'...
0
votes
1
answer
71
views
Unable 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 ...
3
votes
1
answer
99
views
backward 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 app_corp_1.0.X
./app_corp_1....
0
votes
0
answers
103
views
Django ORM sporadically dies when ran in fastAPI endpoints using gunicorn [duplicate]
Other related Questions mention using either
django.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 ...
0
votes
1
answer
137
views
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 ...
0
votes
1
answer
54
views
Django: How to Represent and Query Symmetrical Relationships for a Family Tree?
I am building a family tree application in Django where I need to represent and query marriages symmetrically. Each marriage should have only one record, and the relationship should include both ...
0
votes
1
answer
80
views
Annotate multiple values as JSONObject - parse datetime
I'm annotating my QuerySet as follows, using JSONObject, to obtain multiple fields from Scan:
MyModel.objects.annotate(
myscan=Subquery(
Scan.objects
.all()
.values(data=JSONObject(...
1
vote
2
answers
60
views
Django annotation from different sources
I'm trying to build following annotation, essentially looking up the nin field from a person either from the IDcard or from the Person model.
.annotate(
checkins_scan=Scan.objects.filter(models....
1
vote
1
answer
33
views
How to query a reverse foreign key multiple times in Django ORM
Assuming the following models:
class Store(models.Model):
name = models.CharField(max_length=255)
class Stock(models.Model):
name = models.CharField(max_length=255)
store = models....
0
votes
1
answer
75
views
django, how to use subquery values into outer query
I have a query that uses the values from a subquery. While I'm able to write the subquery in django, I can't write the main query. Here's a little example (the schema is department <-- person <--...
1
vote
2
answers
72
views
django ManyToMany field update
I have trouble with updating calculating_special_order_items, calculating_floor_special_order_items, order_total, ship_total, confirm_total, real_total and calculating_total. When I save a new ...
0
votes
0
answers
13
views
django query_utils empty placeholder
I'd like to use django.db.modles.query_utils.Q, the |-operator and defaultdict to create a (set-)union of different conditions, i.e. to filter anything that matches any of them. Therefore it makes ...
1
vote
1
answer
37
views
Django Query API select_related in multi-table count query
Imagine I'm trying to count the number of tree cultivars in a certain park, and the trees are grouped in specific fields within the park. One catch is that trees can be replanted, so I want to count ...
1
vote
1
answer
160
views
Generic Foreign Key on unsaved model in Django
I have stumbled into a bit of inconsistency with Foreign Keys and Generic Foreign Keys in Django. Suppose we have three models
class Model_One(models.Model):
name= models.CharField(max_length=255)
...
2
votes
1
answer
49
views
Can 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, my_date).annotate(......
2
votes
2
answers
302
views
How to annotate type of Manager().from_queryset()?
In Django I have custom QuerySet and Manager:
from django.db import models
class CustomQuerySet(models.QuerySet):
def live(self):
return self.filter(is_draft=False)
class CustomManager(...
1
vote
3
answers
107
views
How to make group by in django ORM
I've an Order model as below:
class Order(models.Model):
bill = models.ForeignKey(Bill, on_delete=models.PROTECT, null=True, blank=True)
address_from = models.ForeignKey(Address, on_delete=...
0
votes
0
answers
20
views
DRF list api response so slow and cause CPU throttling
An API in my project works fine locally but when it is called in production, it slows the application's response time (all other APIs) and the container workload gets throttled for about 10 seconds.
...
0
votes
2
answers
44
views
Django filter not working when using F() with ManyToMany
I have the following query:
MyModel.objects.filter(foreing_key__value=F('value'))
And It works perfectly. But now I have some complex rules where I need to evaluate the ForeignKey value depending on ...
0
votes
1
answer
93
views
Execute raw SQL before each select for specific model
I have a complicated report in Django, which is written as raw SQL, and than stored in the database as a database view.
I have a Django model (managed=False), tied to that database view, so that I can ...
0
votes
0
answers
62
views
Django Migration file not being created despite showing its name and changes
It started seemingly out of nowhere, I'm unable to trace the origins of this issue but yesterday I made migrations just fine and I'm the only working on the project as of now, when I run python manage....
-1
votes
3
answers
73
views
Count unique values and group by date
I have a table like:
client_id
action
date (datetime)
1
visit
2024-10-10 10:00
1
visit
2024-10-10 12:00
1
visit
2024-10-10 13:00
2
visit
2024-10-10 13:00
So, I need to count amount of unique clients ...
0
votes
1
answer
54
views
Django Chatroom model: Retrieve latest messages from all rooms a user is part of
I'm having a hard time constructing a query (sqlite) to get the latest message for each chatroom a user is part of. This is my model in Django:
class Membership(models.Model):
room_name = models....
0
votes
1
answer
28
views
How to sort values of a query in Django based on the quantity of child table?
I have a Product class that has a child class ProductColors.
These are my two classes:
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products', on_delete=models....
2
votes
1
answer
68
views
Can I reuse output_field instance in Django ORM or I should always create a duplicate?
I have a Django codebase that does a lot of Case/When/ExpressionWrapper/Coalesce/Cast ORM functions and some of them sometimes need a field as an argument - output_field.
from django.db.models import ...
1
vote
1
answer
44
views
django ORM query filter methods running multiple filter duplicates joins
I'm trying to run filters using methods in two separate attributes.
In ICD10Filter:
class Icd10Filter(filters.FilterSet):
# New Filters for DOS Range
dosFrom = filters.DateFilter(method='...
1
vote
0
answers
48
views
Where remove or set initial rows for database in Django?
I store some temporary data in a database linked to a web socket. After a server reboot, the web sockets die and I want to delete all data from the corresponding table. Tell me where ideologically ...
2
votes
1
answer
160
views
Django GeneratedField as ForeignKey with referential integrity
I'm trying to create a generated field that is also a foreign key to another table, while maintaining referential integrity at the database level.
Basically, I'm trying to have the same effect as the ...
1
vote
1
answer
253
views
Annotating a Django QuerySet with the count of a Subquery
I'm building a job board. Each Job could have several associated Location objects.
I have designed my Location and Job models as follows:
class Location(BaseModel):
slug = models.CharField(unique=...
1
vote
0
answers
45
views
Significant performance difference in django view vs. django shell within docker
I'm encountering a significant performance difference when running the same raw SQL query in my Django application. The query executes in about 0.5 seconds in the Django shell but takes around 2 ...
2
votes
0
answers
62
views
If my RPC logic with Django and Pika is inactive for too long, I lose the DB connection and subsequent requests fail with psycopg.OperationalError
The error I get is
psycopg.OperationalError: consuming input failed: server closed the
connection unexpectedly
I am using RabbitMQ as my message broker, though I don't think it's related.
Ultimately,...
-1
votes
1
answer
47
views
Setting Manager for Django models dynamically
I'm trying to set my custom manager dynamically for given models.
Here is a sample of my code
class CustomManager(models.Manager):
def active(self):
return self.filter(name__startswith='c')...
2
votes
1
answer
94
views
Is it possible to switch to a through model in one release? [duplicate]
Assume I have those Django models:
class Book(models.Model):
title = models.CharField(max_length=100)
class Author(models.Model):
name = models.CharField(max_length=100)
books = models....
0
votes
1
answer
103
views
Sort version number of format 1.1.1 in Django
I have a Django model with a release_version char field that stores version information in the format 1.1.1 (e.g., 1.2.3). I need to sort a queryset based on this version field so that versions are ...
0
votes
1
answer
56
views
paginating django prefetch_related queryset results in n+1 queries per row
Each row in the paginated page makes a separate query for each “child” object, instead of prefetching the child objects (n+1 queries).
model.objects.prefetch_related(Prefetch (lookup=“”, queryset=“...
1
vote
3
answers
85
views
order_by combined column in django
I have two models who inherit from another model.
Example:
class Parent(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, verbose_name="ID")
...
0
votes
1
answer
41
views
How to annotate after group by and order_by in django?
I have a DB table which has a field "created_at". This is a auto_now_add=True field.
This table is inserted data once everyday. What I want to do is filter data that corresponds to the last ...
1
vote
1
answer
27
views
Annotate and filter by related model
I have two models:
class ABSLoyaltyCard(models.Model):
title = models.CharField(
max_length=120,
blank=True,
)
class CardToOwner(models.Model):
id = models.UUIDField(...
0
votes
0
answers
42
views
Django ORM - Prevent null field being included in the insert statement [duplicate]
I have a Django model resembling the following:
class SomeClass(CoreModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
auto_increment_id = models....
0
votes
0
answers
44
views
Django, how to get annotated field of related model
For example, the Invoice model has a project field that points a ForeignKey to the Project model, Project has a custom ProjectManager that has get_queryset defined, in get_queryset I do:
super()....