Questions tagged [django-orm]

Django's ORM system, comprising its queryset and model systems.

Filter by
Sorted by
Tagged with
457 votes
18 answers

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 ...
Zags's user avatar
  • 37.6k
427 votes
6 answers

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(...
Elisa's user avatar
  • 6,875
302 votes
1 answer

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)
Ron's user avatar
  • 22.2k
225 votes
4 answers

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 ...
sfendell's user avatar
  • 5,425
195 votes
8 answers

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?
user avatar
175 votes
6 answers

How to rename items in values() in Django?

I want to do pretty much the same like in this ticket at, but with some additonal formatting. From this query >>> MyModel.objects.values('cryptic_value_name') [{'...
Martin's user avatar
  • 4,170
174 votes
6 answers

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) ...
Sai Krishna's user avatar
  • 7,657
170 votes
7 answers

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 ...
Aswin Murugesh's user avatar
166 votes
5 answers

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 ...
alj's user avatar
  • 2,869
166 votes
6 answers

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?
user469652's user avatar
162 votes
6 answers

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(...
gerdemb's user avatar
  • 11.3k
140 votes
6 answers

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 ...
dragoon's user avatar
  • 5,611
134 votes
4 answers

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 ...
jamida's user avatar
  • 2,869
134 votes
10 answers

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 ...
davidchambers's user avatar
112 votes
4 answers

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 ...
Grave_Jumper's user avatar
  • 1,234
109 votes
8 answers

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 ...
zhuyxn's user avatar
  • 6,691
102 votes
2 answers

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....
Timmmm's user avatar
  • 88.6k
101 votes
7 answers

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 ...
Krystian Cybulski's user avatar
101 votes
5 answers

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 ( I guess the issue is assigning m2m field in ...
conf's user avatar
  • 1,013
97 votes
4 answers

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=...
Ali's user avatar
  • 3,568
92 votes
2 answers

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 ...
limasxgoesto0's user avatar
88 votes
4 answers

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 ...
gath's user avatar
  • 24.5k
87 votes
6 answers

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 ...
danny's user avatar
  • 993
86 votes
9 answers

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?
Karnivaurus's user avatar
  • 22.9k
81 votes
3 answers

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. ...
Jackie's user avatar
  • 811
78 votes
9 answers

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. ...
saltycrane's user avatar
  • 6,561
76 votes
5 answers

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....
yossi's user avatar
  • 13k
73 votes
2 answers

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 ...
Adam Lewis's user avatar
  • 7,057
72 votes
8 answers

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 ...
Manoj Govindan's user avatar
68 votes
2 answers

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 '...
Lara's user avatar
  • 2,180
67 votes
2 answers

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 ...
snakesNbronies's user avatar
67 votes
3 answers

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(.....
Dr.Elch's user avatar
  • 2,105
65 votes
4 answers

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(...
Raunak Agarwal's user avatar
54 votes
3 answers

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(...
simplyharsh's user avatar
  • 35.6k
54 votes
2 answers

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) ...
Alex Rothberg's user avatar
51 votes
6 answers

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?
Yuvi's user avatar
  • 4,467
50 votes
4 answers

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 ...
I159's user avatar
  • 29.8k
49 votes
2 answers

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 ...
John Moutafis's user avatar
49 votes
5 answers

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'...
user469652's user avatar
48 votes
4 answers


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(...
hanleyhansen's user avatar
  • 6,304
48 votes
4 answers

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....
user3599803's user avatar
  • 6,445
47 votes
3 answers

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. ===...
Todor's user avatar
  • 15.4k
46 votes
3 answers

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 ...
svintus's user avatar
  • 1,582
45 votes
6 answers

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 ...
mpen's user avatar
  • 273k
45 votes
5 answers

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 ...
Kieran Lynn's user avatar
43 votes
3 answers

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. ...
mpen's user avatar
  • 273k
43 votes
4 answers

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 ...
Leonid Shifrin's user avatar
39 votes
4 answers

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
Alex's user avatar
  • 795
39 votes
1 answer

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 ...
rick's user avatar
  • 4,101
37 votes
4 answers

Django Blob Model Field

How do you store a "blob" of binary data using Django's ORM, with a PostgreSQL backend? Yes, I know Django frowns upon that sort of thing, and yes, I know they prefer you use the ImageField or ...
Cerin's user avatar
  • 61.1k

2 3 4 5