Questions tagged [django-orm]
Django's ORM system, comprising its queryset and model systems.
4,042
questions
474
votes
18
answers
385k
views
Convert Django Model object to dict with all of the fields intact
How does one convert a django Model object to a dict with all of its fields? All ideally includes foreign keys and fields with editable=False.
Let me elaborate. Let's say I have a django model like ...
435
votes
6
answers
298k
views
How to perform OR condition in django queryset?
I want to write a Django query equivalent to this SQL query:
SELECT * from user where income >= 5000 or income is NULL.
How to construct the Django queryset filter?
User.objects.filter(...
312
votes
1
answer
161k
views
How to query Case-insensitive data in Django ORM?
How can I query/filter in Django and ignore the cases of my query-string?
I've got something like and like to ignore the case of my_parameter:
MyClass.objects.filter(name=my_parameter)
231
votes
4
answers
108k
views
Django self-referential foreign key
I'm kind of new to webapps and database stuff in general so this might be a dumb question. I want to make a model ("CategoryModel") with a field that points to the primary id of another instance of ...
199
votes
8
answers
130k
views
How to view corresponding SQL query of the Django ORM's queryset?
Is there a way I can print the query the Django ORM is generating?
Say I execute the following statement: Model.objects.filter(name='test')
How do I get to see the generated SQL query?
180
votes
6
answers
100k
views
How to rename items in values() in Django?
I want to do pretty much the same like in this ticket at djangoproject.com, but with some additonal formatting. From this query
>>> MyModel.objects.values('cryptic_value_name')
[{'...
176
votes
6
answers
132k
views
How to create an object for a Django model with a many to many field?
My model:
class Sample(models.Model):
users = models.ManyToManyField(User)
I want to save both user1 and user2 in that model:
user1 = User.objects.get(pk=1)
user2 = User.objects.get(pk=2)
...
175
votes
7
answers
164k
views
What is the SQL ''LIKE" equivalent on Django ORM queries?
What is the equivalent of the following SQL statement in Django?
SELECT * FROM table_name WHERE string LIKE pattern;
I tried this:
result = table.objects.filter( pattern in string )
but it didn't ...
175
votes
5
answers
199k
views
Select 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 ...
172
votes
6
answers
251k
views
Django database query: How to get object by id?
Django automatically creates an id field as primary key.
Now I need to get the object by this id.
object = Class.objects.filter()
How to write this filter?
164
votes
6
answers
201k
views
Chaining multiple filter() in Django, is this a bug?
I always assumed that chaining multiple filter() calls in Django was always the same as collecting them in a single call.
# Equivalent
Model.objects.filter(foo=1).filter(bar=2)
Model.objects.filter(...
141
votes
6
answers
94k
views
Django select only rows with duplicate field values
suppose we have a model in django defined as follows:
class Literal:
name = models.CharField(...)
...
Name field is not unique, and thus can have duplicate values. I need to accomplish the ...
136
votes
4
answers
223k
views
Select DISTINCT individual columns in django?
I'm curious if there's any way to do a query in Django that's not a "SELECT * FROM..." underneath. I'm trying to do a "SELECT DISTINCT columnName FROM ..." instead.
Specifically I have a model that ...
136
votes
10
answers
72k
views
Why is iterating through a large Django QuerySet consuming massive amounts of memory?
The table in question contains roughly ten million rows.
for event in Event.objects.all():
print event
This causes memory usage to increase steadily to 4 GB or so, at which point the rows print ...
113
votes
4
answers
114k
views
Django filter many-to-many with contains
I am trying to filter a bunch of objects through a many-to-many relation. Because the trigger_roles field may contain multiple entries I tried the contains filter. But as that is designed to be used ...
111
votes
8
answers
239k
views
How to update() a single model instance retrieved by get() on Django ORM?
I have a function which currently calls Models.object.get(), which returns either 0 or 1 model objects:
if it returns 0, I create a new model instance in the except DoesNotExist clause of the ...
107
votes
5
answers
132k
views
Direct assignment to the forward side of a many-to-many set is prohibited. Use emails_for_help.set() instead
I am new to Django and didn't find any reference regarding this issue. I am getting this error when i use many to many field in Django model (models.py). I guess the issue is assigning m2m field in ...
105
votes
2
answers
88k
views
Why does django's prefetch_related() only work with all() and not filter()?
suppose I have this model:
class PhotoAlbum(models.Model):
title = models.CharField(max_length=128)
author = models.CharField(max_length=128)
class Photo(models.Model):
album = models....
103
votes
7
answers
85k
views
In a Django QuerySet, how to filter for "not exists" in a many-to-one relationship
I have two models like this:
class User(models.Model):
email = models.EmailField()
class Report(models.Model):
user = models.ForeignKey(User)
In reality each model has more fields which are ...
102
votes
5
answers
93k
views
Django equivalent of SQL not in
I have a very simple query: select * from tbl1 where title not in('asdasd', 'asdasd').
How do I translate that to Django? It's like I want the opposite of: Table.objects.filter(title__in=...
93
votes
6
answers
90k
views
Django: order_by multiple fields
I am getting order_by fields in the form of a list.
I want to order by multiple fields with Django ORM.
List is like below:
orderbyList = ['check-in','check-out','location']
I am writing a query like ...
92
votes
4
answers
111k
views
How to use "AND" in a Django filter?
How do I create an "AND" filter to retrieve objects in Django? e.g I would like to retrieve a row which has a combination of two words in a single field.
For example the following SQL query ...
92
votes
2
answers
25k
views
Example of what SQLAlchemy can do, and Django ORM cannot
I've been doing a lot of research lately into using Pyramid with SQLAlchemy versus keeping a current application in Django. That by itself is an entire debate, but I'm not here to discuss that.
What ...
86
votes
9
answers
206k
views
List field in model?
In my model, I want a field that has a list of triplets. e.g. [[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]]. Is there a field that can store this data in the database?
81
votes
3
answers
42k
views
Annotating a Sum results in None rather than zero
I'm making a QA site that is similar to the page you're on right now. I'm attempting to order answers by their score, but answers which have no votes are having their score set to None rather than 0. ...
78
votes
9
answers
9k
views
How to work around lack of support for foreign keys across databases in Django
I know Django does not support foreign keys across multiple databases (originally Django 1.3 docs)
But I'm looking for a workaround.
What doesn't work
I have two models each on a separate database.
...
77
votes
5
answers
36k
views
Django orm get latest for each group
I am using Django 1.6 with Mysql.
I have these models:
class Student(models.Model):
username = models.CharField(max_length=200, unique = True)
class Score(models.Model):
student = models....
76
votes
2
answers
146k
views
Django model method - create_or_update
Similar to get_or_create, I would like to be able to update_or_create in Django.
Until now, I have using an approaching similar to how @Daniel Roseman does it here. However, I'd like to do this more ...
75
votes
8
answers
35k
views
Django: is there a way to count SQL queries from an unit test?
I am trying to find out the number of queries executed by a utility function. I have written a unit test for this function and the function is working well. What I would like to do is track the number ...
75
votes
2
answers
44k
views
What is the default order of a list returned from a Django filter call?
Short Question
What is the default order of a list returned from a Django filter call when connected to a PostgreSQL database?
Background
By my own admission, I had made a poor assumption at the ...
71
votes
3
answers
84k
views
Django ORM - objects.filter() vs. objects.all().filter() - which one is preferred?
Very often I see constructs like
MyModel.objects.all().filter(...)
which will return a QuerySet of the default Mananger. At first all() seems to be quite redundant, because
MyMode.objects.filter(.....
70
votes
2
answers
43k
views
Django Aggregation - Expression contains mixed types. You must set output_field
I'm trying to achive an Aggregation Query and that's my code:
TicketGroup.objects.filter(event=event).aggregate(
total_group=Sum(F('total_sold')*F('final_price')))
I have '...
66
votes
5
answers
54k
views
Django Aggregation: Summation of Multiplication of two fields
I have a model something like this:
class Task(models.Model):
progress = models.PositiveIntegerField()
estimated_days = models.PositiveIntegerField()
Now I would like to do a calculation Sum(...
59
votes
3
answers
20k
views
django-orm case-insensitive order by
I know, I can run a case insensitive search from DJango ORM. Like,
User.objects.filter(first_name__contains="jake")
User.objects.filter(first_name__contains="sulley")
User.objects.filter(...
55
votes
2
answers
35k
views
prefetch_related for multiple Levels
If my Models look like:
class Publisher(models.Model):
pass
class Book(models.Model):
publisher = models.ForeignKey(Publisher)
class Page(models.Model):
book = models.ForeignKey(Book)
...
53
votes
2
answers
60k
views
How to execute a GROUP BY ... COUNT or SUM in Django ORM?
Prologue:
This is a question arising often in SO:
Django Models Group By
Django equivalent for count and group by
How to query as GROUP BY in django?
How to use the ORM for the equivalent of a SQL ...
52
votes
4
answers
30k
views
How to use custom manager with related objects?
I have a custom manager. I want to use it for related objects. I found use_for_related_fields in docs. But it does not work the way I used it:
class RandomQueryset(models.query.QuerySet):
def ...
51
votes
6
answers
78k
views
Default image for ImageField in Django's ORM
I'm using an ImageField to store profile pictures on my model.
How do I set it to return a default image if no image is defined?
50
votes
5
answers
34k
views
In Django, how do you make a model refer to itself?
Assume we have class Employee. I want to have a field which references a different instance of the same class.
How to write this? How about the following code?
ref_employee= models.ForeignKey('self'...
50
votes
5
answers
55k
views
django select_related - when to use it
I'm trying to optimize my ORM queries in django. I use connection.queries to view the queries that django generate for me.
Assuming I have these models:
class Book(models.Model):
name = models....
49
votes
4
answers
96k
views
LEFT JOIN Django ORM
I have the following models:
class Volunteer(models.Model):
first_name = models.CharField(max_length=50L)
last_name = models.CharField(max_length=50L)
email = models.CharField(...
49
votes
3
answers
22k
views
Is 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 prefetches.
===...
47
votes
3
answers
80k
views
How to make Django QuerySet bulk delete() more efficient
Setup:
Django 1.1.2, MySQL 5.1
Problem:
Blob.objects.filter(foo = foo) \
.filter(status = Blob.PLEASE_DELETE) \
.delete()
This snippet results in the ORM first generating a ...
46
votes
6
answers
26k
views
How to force Django Admin to use select_related?
One of my models is particularily complex. When I try to edit it in Django Admin it performs 1042 queries and takes over 9 seconds to process.
I know I can replace a few of the drop-downs with ...
45
votes
5
answers
39k
views
Serializing Foreign Key objects in Django
I have been working on developing some RESTful Services in Django to be used with both Flash and Android apps.
Developing the services interface has been quite simple, but I have been running into ...
43
votes
3
answers
12k
views
Django: Force select related?
I've created a model, and I'm rendering the default/unmodified model form for it. This alone generates 64 SQL queries because it has quite a few foreign keys, and those in turn have more foreign keys.
...
43
votes
4
answers
26k
views
Aggregation of an annotation in GROUP BY in Django
UPDATE
Thanks to the posted answer, I found a much simpler way to formulate the problem. The original question can be seen in the revision history.
The problem
I am trying to translate an SQL query ...
41
votes
4
answers
19k
views
In Django filter statement what's the difference between __exact and equal sign (=)?
In Django filter statement what's the difference if I write:
.filter(name__exact='Alex')
and
.filter(name='Alex')
Thanks
39
votes
1
answer
48k
views
Does Django queryset values_list return a list object?
I have a Django app where users post photos, and other leave comments under the photos.
When a comment is left, I need to notify:
Everyone else who wrote in this thread
The owner of the photo, in ...
39
votes
1
answer
15k
views
Does get_or_create() have to save right away? (Django)
I need to use something like get_or_create() but the problem is that I have a lot of fields and I don't want to set defaults (which don't make sense anyway), and if I don't set defaults it returns an ...