298 questions
2
votes
1
answer
100
views
Django: Annotate queryset based on the existence of many-to-many relationships
I am using Django 5.2 with Postgres 17 and try to modify the queryset of a ListView for row-based access control. Items are to be included in the queryset either if the user is part of a project that ...
1
vote
0
answers
58
views
Count distinct on an aggregated dimension
I have the following model:
class Historique(models.Model):
type_of_object_choices = (
(1, 'Cadeau')
, (2, 'Offre')
, (3, 'Commentaire')
)
event_type_choices = ...
0
votes
1
answer
37
views
Django create() not applying annotations applied on manager
Imagine the following model, manager and queryset:
from django.db import models
class BlaQuerySet(models.QuerySet):
def annotate_field(self):
return self.annotate(bla_field=Value('Bla')
...
0
votes
0
answers
49
views
django using aggregate() and distinct() together
I have a filterset that has following attributes:
dosFromGte = filters.DateFilter(method="search_by_dos_from_gte", lookup_expr="gte")
dosToLte = filters.DateFilter(method="...
1
vote
1
answer
156
views
Django Annotation F() value
I have a question regarding Django Annotations:
tickers = {
"BCO": 10.0,
"AIR": 50.0,
}
assets = Asset.objects.annotate(
price=(tickers[F("...
0
votes
1
answer
57
views
Python Django Annotations over multiple relationships
I have a question On Django annotations. Here is my model:
class Asset(models.Model):
security = models.ForeignKey(Security, on_delete=models.CASCADE, blank=False)
class Batch(models.Model):
...
0
votes
1
answer
58
views
Django ORM Query aggregate datetime + timeoffset and filter on new value
I've the following table structure (note localised start time):
id
start_time
offset
score
1
2024-06-14 02:03:00.000 +0200
+1000
15
2
2024-06-14 02:04:00.000 +0200
+1000
15
3
2024-06-14 02:05:00.000 +...
0
votes
1
answer
133
views
How to build single query in Django with related models and count
I did not use the Django for a years and tried to modify some old codebase today.
I have models:
class MetaTemplate(CreatedModifiedBase):
type = models.CharField(max_length=200)
class Project(...
0
votes
1
answer
99
views
annotating an object with a list of objects related to it but filtered down
I have the following objects (simplified just for this question)
class Object1(models.Model):
users_assigned_to_object1 = models.ManyToMany(Users, related_name='objects')
sub_object = models....
3
votes
2
answers
407
views
Django-cte gives: 'QuerySet' object has no attribute 'with_cte'
I have records in below format:
| id | name | created |
-----------------------------------------------
|1 | A |2024-04-10T02:49:47.327583-07:00|
|2 | A |2024-04-...
0
votes
0
answers
112
views
Django: how to annotate average of average?
I have a Puzzle model and a Session model
During a session, user will play puzzles and rate them. result is recorded through the following model:
class Play(models.Model):
puzzle = models....
1
vote
1
answer
38
views
I'm getting incorrect values when counting annotations
When I filter with one or two tags, the number of likes is displayed correctly. However, if I filter by three tags, the number of likes is multiplied by the number of tags associated with the question....
0
votes
1
answer
77
views
How to Implement in Annotate and Filter in Django
This is a follow up to a previous question but I will include all the detail here.
I'm creating a game where one of the elements is that players vote for each other.
Here are the models I've set up (...
1
vote
1
answer
242
views
Annotate Django Foreign Key model instance
Is it possible in Django to annotate a Foreign Key instance?
Suppose I have the following models:
class BaseModel(models.Model):
pass
class Foo(models.Model):
base_model = models.ForeignKey('...
3
votes
1
answer
1k
views
Order Django queryset by annotated field and annotate it again
I need to order Django queryset by annotated field and then annotate result with row number.
Steps:
Add complex_order field to QuerySet that defines extra logic for future ordering.
Order QuerySet by ...
1
vote
1
answer
76
views
Django: SUM of COUNT in annotations
I have the following simple models:
class Member(models.Model):
name = models.CharField(max_length=100)
class Booking(models.Model):
date = models.DateField(default=now)
price = models....
0
votes
1
answer
42
views
Manager's annotations don't show up when traversing ForeignKey
Suppose I have such classes:
class UserManager(Manager):
def get_queryset(self):
return super().get_queryset().annotate(
full_name=Concat(
F('first_name'), ...
1
vote
0
answers
136
views
How to set date_hierarchy to an annotation field
I have a Model and its Manager. I created an annotated field date (which returns not null date from start or set date).
class TimerManager(models.Manager):
def get_queryset(self):
return (
...
1
vote
1
answer
95
views
Get average of annotated fields in Django (postgres)
Consider the following models:
class Employee(models.Model):
name = models.Charfield(max_length=100)
class Evaluation(models.Model):
employee = models.ForeignKeyField(Employee, on_delete=...
1
vote
1
answer
42
views
Annotating Many2Many link works but only on SQLite (testing) not MariaDB (Production)
I am trying to annotate a model that includes a many2many field:
class Link(models.Model):
products = models.ManyToManyField(Product, related_name = "%(class)s_name", related_query_name =...
0
votes
1
answer
30
views
Access Foreign Key's Queryset
I have these models:
class Source(models.Model):
name = models.CharField(max_length=255, blank=True, null=True)
feed_url = models.CharField(max_length=512)
....
class Post(...
0
votes
1
answer
113
views
having problem to use annotate in django to return nested list
I have a model in django named Courses and it has a ManyToManyField which is related to the teachers Model. now in the views file I'm gonna make an APIView to return a list of courses which each ...
0
votes
1
answer
1k
views
Django ORM: This queryset contains a reference to an outer query and may only be used in a subquery
In the queryset, I want to get the average of what subquery returns and then group by 'store_id' and 'avg_sales'. However, when I used the following queries:
subquery = StoreStatistics.objects.filter(
...
0
votes
1
answer
24
views
Group by then annotate following relationships backwards in django
I can sum all payments for each Klient. But I need to know sum each type of payment.
Here are my models:
class Klient(models.Model):
name = models.CharField(max_length=30)
surname = models....
1
vote
1
answer
67
views
Django Queryset: group by two field values
I have a model like this
Class ExchangeMarket(models.Model):
base_currency = models.ForeignKey(Currency)
quote_currency = models.ForeignKey(Currency)
... various other fields
And some entries like
...
0
votes
1
answer
60
views
Django - Annotating, Filtering and Sorting on a none to many relationships doesn't work
I am working on a table that display a list of orders with the option to filter and to sort depending either to direct attribute of the order or indirectly to attribute of related models. The two ...
1
vote
1
answer
266
views
How to print object's values with "annotate()" and "for loop" in ascending order?
I have Category and Product models below. *I use Django 3.2.16:
# "models.py"
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=20)
class ...
0
votes
1
answer
363
views
How can I annotate django-polymorphic models that have GenericRelations to other models with GenericForeignKeys?
I have a parent model named Content that inherits from Django polymorphic. This is a simplified example, but I have a Post model that inherits from Content.
On the Content model, notice that I have a ...
2
votes
2
answers
461
views
Django annotate(),Count()
I get the output like this using annotate() and Count()
<QuerySet [{'pid': 11, 'status': 'Completed', 'status__count': 3}, {'pid': 11, 'status': 'Hold', 'status__count': 12}, {'pid': 11, 'status': '...
3
votes
1
answer
1k
views
Django annotate field value from external dictionary
Lets say I have a following dict:
schools_dict = {
'1': {'points': 10},
'2': {'points': 14},
'3': {'points': 5},
}
And how can I put these values into my queryset using annotate?
I would ...
1
vote
1
answer
467
views
django annotate with dynamic "then" value
So i have this dictionary of months below:
MONTHS = {
1: "Janeiro",
2: "Fevereiro",
3: "Março",
4: "Abril",
5: "Maio",
6: &...
-1
votes
1
answer
235
views
how to take average of every 10 minutes of a model django
I am using multiple APIs and saving them to the database. I have one model called Station (it has a DateTime field and some other fields) and every API is for one station. These APIs come from devices ...
0
votes
0
answers
235
views
ORM Django annotate to convert string field to sorted list
I have a table containing a string field with a value like the following:
'["value1", "value3", "value2"]'.
Using the Django ORM, I require to convert that string type ...
0
votes
2
answers
31
views
Get average of multiple ratings values from different model instances (Django)
I'm working on this web-app that lets a project manager rate a vendor after finishing a task/job.
Here is the models.py content:
class Rating(models.Model):
RATE_CHOICES = [
(1, 'Below ...
0
votes
1
answer
221
views
How to delete everything but the latest object in each group in Django
I want to group my model objects by three fields, and delete all objects but the youngest for each group.
My model:
class DataFile(models.Model):
filename = models.CharField(unique=True, ...
0
votes
1
answer
174
views
Get extra field via annotate in Django many to many relation
I have a m2m relation between a Feature model and the User model through an intermediary table. Feature model represents all the available features, and a User can enable or disable zero, one or more ...
0
votes
1
answer
319
views
Django - annotate the most frequent field taken from another model linked with foreignKey
I have a model of users and a model with a survey in which users express their opinion with a vote with an integer number that identified a particular color of eyes. A srcID user describes the color ...
1
vote
1
answer
1k
views
How to cast django.db.models F to a String?
Note: working on expensive corporate legacy code and models that are not allowed to be changed
What I'm trying to do:
Combine two fields into one as a DateTime field.
Model.py:
from django.db import ...
0
votes
1
answer
207
views
How to get annotated attributes in a template from a DetailView?
I'm working on a small e-commerce. For a model 'Product' I keep track of the stock using a Custom Manager and a method called Products.objects.with_stock() that uses annotations (I'm required to do so,...
2
votes
2
answers
302
views
How to group by and get latest record in group contain all of fields in Django?
Imagine we have a table like this:
id
name
type
created_at
1
James
male
2022-03-02
2
Jane
female
2022-04-02
3
Kirk
male
2022-03-04
4
Sarah
female
2022-04-04
5
Jason
male
2022-03-05
And i want to group ...
1
vote
2
answers
726
views
How to Django queryset annotate True when all BooleanField of related objects are True else False?
I have a model who looks like this :
class Test(models.Model):
user = models.ForeignKey('users.CustomUser', models.CASCADE)
name = models.CharField(max_length=64)
class TestVersion(models....
0
votes
0
answers
32
views
Django annotate and aggregate not suport Timefild for sum
How can I make the total time sum of each user being that annotate and aggregate have no support for Timefild
Models:
class Pireps(models.Model):
...
flight_time = models.TimeField(auto_now=...
1
vote
2
answers
308
views
Annotate results from related model method onto model Queryset?
I'm trying to figure out the best / most efficient way to get the 'progress' of a Summary object. A Summary object has X Grade objects - a Grade object is_complete when it has a Level chosen and has 1 ...
0
votes
2
answers
126
views
Counting the children matching grandchildren conditions in a single Django query
Given the following models:
class Flight:
class Checklist:
flight = ForeignKey(Flight)
class Item:
checklist = ForeignKey(Checklist)
completed = BooleanField()
I need to get the number ...
1
vote
2
answers
260
views
Django annotate count of subquery items - ValueError: This queryset contains a reference to an outer query and may only be used in a subquery
I have an Agent, Client and Car models.
In Client model: agent = ForeignKey('Agent'...)
In Car model: client = ForeignKey('Client'...)
I want to annotate (on an Agent QuerySet) a total number of ...
0
votes
1
answer
1k
views
Django annotate count for another queryset
Models:
class Regions(models.Model):
name = models.CharField(max_length=255, unique=True)
class Owners(models.Model):
name = models.CharField(max_length=255, null=False, unique=True)
url = ...
0
votes
1
answer
107
views
annotation in admin list with many to many relation
I have a link between ads and products and stores, and I want to sort them in the admin by store:
class Ad(models.Model):
products = models.ManyToManyField(Product, blank = True)
device = ...
2
votes
1
answer
2k
views
sorting 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",...
1
vote
1
answer
73
views
Is it possible to use aggregate on a queryset annotation?
I am using annotate on a django queryset:
class MyModel(models.Model):
my_m2m = models.ManytoManyField()
my_qs = MyModel.objects.all().annotate(total_m2m=Count('my_m2m'))
This yields the desired ...
1
vote
1
answer
243
views
annotating by one-to-many relationship in Django
Let's say I have these two models:
class Test1:
...........
class Test2:
test1 = models.ForeignKey(Test1, related_name = 'tests')
isCompleted = models.BooleanField()
and I want to make ...