6,857 questions
3
votes
1
answer
51
views
Count distinct values of Subquery
I've got these models:
class Component(models.Model)
name = models.CharField(max_length=50)
class ComponentAttribute(models.Model)
component = models.ForeignKey(Component)
context = ...
2
votes
1
answer
59
views
Django filter an m2m relation by a list of inputs (which must all match)
Let's take some Store and Book models as examples:
class Book(Model):
title = CharField(...)
...
class Store(Model):
books = ManyToManyField('Book', blank=True, related_name='stores')
...
0
votes
1
answer
90
views
Django REST Framework `pagination_class` on ViewSet is ignored
Describe the Problem
I have a ModelViewSet in Django REST Framework designed to return a list of Order objects. To improve performance, I'm trying to implement custom pagination that limits the ...
1
vote
1
answer
56
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 ...
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
54
views
QuerySet returns empty in django
I am trying to get the book list with 3 conditions:
Accession number (character varying,10)
Physical location (character varying,20)
Book status
Based on the user input:
Accession number should be ...
0
votes
1
answer
72
views
How to check if a django queryset has a matching manytomany + foreignkey?
I try to check - in Django - if a user-made queryset has two fields which match 100%.
class Foo(models.Model):
# ...
free_field = models.ForeignKey(FreeModel, ...)
must_match_m2m_field = ...
0
votes
1
answer
90
views
How to deal with recurrence dates in Django?
I'm currently developing a Gym website and using django-recurrence to handle recurring training sessions.
However, I'm unsure how to work with recurrence dates in a Django QuerySet. Specifically, I ...
1
vote
1
answer
91
views
Django queryset annotate sum of related objects of related objects
I have
class Book(models.Model):
title = models.CharField(max_length=32)
class Table(models.Model):
book = models.ForeignKey(Book, related_name='tables')
class TableEntry(models.Model):
...
0
votes
0
answers
59
views
Create a Django custom Transform from an annotation
I've got an annotation for a foreign key field that I use frequently and would like to write a custom Django Transform which behaves similar to the annotation. The annotation that does what I would ...
0
votes
1
answer
58
views
Custom generic istruthy/isfalsy lookup doesn't work on Foreign Keys
In my Django project, I'm in need of a generic istruthy/isfalsy lookup that would work on any type of database field.
Example of models.py:
class MyModel(models.Model):
my_charfield = models....
-1
votes
1
answer
73
views
How to add element in Django QuerySet?
I have model Report and GroupReport. They have many-to-many relation.
I can easily get QuerySet[GroupReport] for all GroupReport instance:
Group Name 1:
Report Name 1
Report Name 2
Group ...
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 = ...
1
vote
0
answers
52
views
Django QuerySet performance
I'm debugging sitemap generation, and finally have the following snippet:
items=Event.objects.all()
for limit in (1000, 10000, 20000):
events=items[:limit]
...
4
votes
1
answer
291
views
Django admin inline performing too many queries when having additional ForeignKey
I have the following Django models:
from django.db import models
from django.utils.translation import gettext_lazy as _
class Enterprise(models.Model):
nome = models.CharField(max_length=255)
...
0
votes
1
answer
58
views
Anotation after filter (freeze queryset) Django
In the process of model annotation there is a need to filter the finished list. But the value of the annotation "rank" after the filter() becomes "1" because it has only one ...
0
votes
1
answer
73
views
Optimizing Django QuerySet with Nested Aggregations
I’m working on optimizing a complex Django query where I need to perform nested aggregations and conditional annotations across multiple related models. I want to fetch the top 5 most active users ...
0
votes
1
answer
42
views
Unable to exclude foreign keys in django
I'm failing to get Profiles whithout an Interaction. Does anybody see what I'm doing wrong?
#models.py
class Profile(models.Model):
username = models.CharField(max_length=100)
class ...
1
vote
1
answer
73
views
How can I annotate my Django queryset with a count of related objects
I have 3 django models; Machine, Component, and Part.
I am trying to annotate a machine queryset to include the count of unique parts used in that machine.
In the example below, ps1 is used to make f1....
-1
votes
1
answer
68
views
How to filter Longitude/Latitude on Django PointField directly?
I want to filter directly on a lat/lng value on a GeoDjango PointField.
e.g. geolocation__lat__lte=40.0
Typically in django i can access Latitude/Longitude directly like geolocation.x or geolocation.y ...
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=“...
0
votes
0
answers
45
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()....
0
votes
2
answers
62
views
Django queryset count with zero
I have this Django Model :
class Survey(models.Model):
call = models.OneToOneField(Call, null=True, related_name='survey', on_delete=models.CASCADE)
service = models.ForeignKey(Service, ...
0
votes
1
answer
59
views
How to Rank Students Based on Total Points in Django QuerySet When Filtering Results
I'm working on a Django application where I need to rank students based on their total points and then filter the results. I want to rank all students based on their total points but only show ...
1
vote
1
answer
212
views
Django Query calculate date with `relativedelta` error: can't adapt type 'relativedelta'
I'm facing a tricky problem and couldn't find a solution online. I hope someone here can help me figure out a "clean" way to do this.
This is my current function to retrieve all expired ...
0
votes
1
answer
80
views
Django how to sort by fields that don't exist
Currently, I have two models
posts.models
from django.db import models
from django_prometheus.models import ExportModelOperationsMixin
from users.models import User
from category.models import ...
-1
votes
1
answer
134
views
Django model's relationships and fetching (or excluding) related data from database [duplicate]
I'm having a hard time finding a decent explanation about this in django's official documentation, so I'll ask my question here.
in django 5.0 if two models have a relationship (let's call them Model1 ...
2
votes
1
answer
100
views
How to LEFT OUTER JOIN without foreign key using django orm
I have following Models:
class User(Model):
###
user fields
###
class CaseModel(Model):
id = # django build in id field
owner = models.ForeignKey('User')
###
other ...
1
vote
1
answer
68
views
Django ORM model default not applying in python queryset
I have the below Django ORM which represents a PostgreSQL view.
For the field cost_requirement I have set the default value to 0. However the queryset object still populates with None if data is ...
2
votes
0
answers
45
views
Custom Django Transform with case statement for casting a string to either int or null
I'm trying to create a custom django lookup as_int so that you can easily compare and order the contents of text fields when they contain only a number, and treat them as NULL when they have the wrong ...
1
vote
0
answers
37
views
Django query for a select item return '---------'
I'm trying to populate a select item with a django queryset.
It's working fine but at the begining of the list of the dropdown menu on the select item I always have a '---------' as first option.
...
1
vote
1
answer
33
views
How can I output a selection of Blog objects in a ListView in Django searched via ForeignKeys of two other different models?
I have three models like this:
1:
class Blog(models.Model):
title = models.CharField()
published = models.DateField()
...
2:
class AuthorList(models.Model):
blog = models.ForeignKey(...
1
vote
1
answer
45
views
How to fetch data with the given order from the database ? (django)
I have a model in which there are different fields of data, and a field of "section-order" is given. now i want to fetch that data into the bootstrap accordians with respect to the "...
0
votes
1
answer
110
views
How to get counts based on multiple conditions with grouping in a single query in django orm?
Suppose that I have the following customer model:
class Customer(models.Model):
name = models.CharField()
city = models.CharField()
first_joined = models.DateField(auto_now_add=True)
...
1
vote
1
answer
56
views
Order Django QuerySet by where a term appears in results
I'm trying to implement an autocomplete for an input field using Django and jQuery (user searches for a food from a menu). The problem is figuring out how to order the results.
If, for example, the ...
0
votes
0
answers
36
views
How to efficiently convert denormalized data to JSON?
I am learning django and couldn't find an answer on this.
I am receiving data a query in denormalized form. Here is how it looks like.
Store_id
Shelf_id
Product_id
Qty
store1
shelf1
product1
20
store1
...
0
votes
1
answer
54
views
Annotate django queryset based on related field attributes [duplicate]
Suppose you have this models structure in a django project
from django.db import models
class Object(models.Model):
name = models.CharField(max_length=100)
class ObjectEvent(models.Model):
...
1
vote
1
answer
42
views
How to filter a queryset by a many2many field
I have a Notification model which has a field called seen_users like so:
from django.contrib.auth import get_user_model
User = get_user_model()
class Notification(models.Model):
title = models....
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(...
1
vote
2
answers
52
views
Filter a query set depending on state at a given date
Given the following model (using django-simple-history):
class MyModel (models.Model):
status = models.IntegerField()
history = HistoricalRecords()
I would like to get all instances that didn'...
-3
votes
1
answer
117
views
How to use variable instead of giving field in filter queryset django
if I have a class like this:
class Name: field1 = ... field2 = ... ...
I do not know what are the fields or model it should be given by user so key is going to be name of field in a model and value ...
0
votes
1
answer
33
views
Is this possible in Django ORM? I want to query on reverse foreign key relation ship. I need quite a few queries from the database
What I have?
I have models as below.
class Product(models.Model):
title = models.CharField(max_length=500)
timestamp = models.DateTimeField(auto_now_add=True)
updated = models....
1
vote
1
answer
58
views
Django queryset not filtering correctly in ListView with complex lookup
I'm trying to build a Django application where I have a ListView that displays a list of objects based on complex filtering criteria, but I'm encountering issues with the queryset not filtering ...
0
votes
1
answer
81
views
Filter deep nested related_set in Django
There are two models:
class Subject(Model):
categories = ManyToManyField(Category, related_name='subjects')
class Category(Model):
parent = ForeignKey('self', related_name='subcategories')
...
1
vote
1
answer
78
views
Django REST Framework: can't properly annotate values to many-to-many model, keep getting error Field name <field> is not valid for model <m2m model>
I have a model for recipes and many-to-many model that represents favorite recipes by users:
class Recipe(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
name = ...
1
vote
1
answer
64
views
How to add a duplicate column to a table?
I am retrieving data from the database using Django ORM:
ws = Ws.objects.all()
ws = ws.filter(*q_objects, **filter_kwargs)
ws = ws.order_by(*sort_list)
ws = ws.annotate(created_unix=UnixTimestamp(F('...
1
vote
2
answers
69
views
Can't add value to table Django DataBase
Sorry I am beginer in django try to make app for appointment for doctors and could not solved this problem
I can't add value in to Appoiment Db in to django app
this is my models.py
from django.db ...
0
votes
1
answer
168
views
django-tables2 sorting on custom column
The django-tables2 docs describe how to sort a custom column (https://django-tables2.readthedocs.io/en/latest/pages/ordering.html#table-order-foo-methods). But I can't figure out how to apply this to ...
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....
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 (...