Questions tagged [django-queryset]
Django querysets are the primary abstraction for retrieving objects from Django's ORM system
6,839
questions
978
votes
17
answers
709k
views
How do I do a not equal in Django queryset filtering?
In Django model QuerySets, I see that there is a __gt and __lt for comparative values, but is there a __ne or != (not equals)? I want to filter out using a not equals. For example, for
Model:
bool ...
832
votes
16
answers
473k
views
How to combine multiple QuerySets in Django?
I'm trying to build the search for a Django site I am building, and in that search, I am searching across three different models. And to get pagination on the search result list, I would like to use a ...
628
votes
9
answers
522k
views
How to filter empty or NULL names in a QuerySet?
I have first_name, last_name & alias (optional) which I need to search for. So, I need a query to give me all the names that have an alias set.
Only if I could do:
Name.objects.filter(alias!="")
...
487
votes
8
answers
300k
views
How do I do an OR filter in a Django query?
I want to be able to list the items that either a user has added (they are listed as the creator) or the item has been approved.
So I basically need to select:
item.creator = owner or item.moderated ...
483
votes
10
answers
605k
views
How to delete a record in Django models?
I want to delete a particular record like:
delete from table_name where id = 1;
How can I do this in a django model?
459
votes
4
answers
385k
views
How can I filter a Django query with a list of values?
I'm sure this is a trivial operation, but I can't figure out how it's done.
There's got to be something smarter than this:
ids = [1, 3, 6, 7, 9]
for id in ids:
MyModel.objects.filter(pk=id)
I'...
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(...
421
votes
5
answers
275k
views
Getting the SQL from a Django QuerySet
How do I get the SQL that Django will use on the database from a QuerySet object? I'm trying to debug some strange behavior, but I'm not sure what queries are going to the database.
396
votes
24
answers
367k
views
How do I get the object if it exists, or None if it does not exist in Django?
When I ask the model manager to get an object, it raises DoesNotExist when there is no matching object.
go = Content.objects.get(name="baby")
Instead of DoesNotExist, how can I have go be ...
375
votes
8
answers
510k
views
How do I filter query objects by date range in Django?
I've got a field in one model like:
class Sample(models.Model):
date = fields.DateField(auto_now=False)
Now, I need to filter the objects by a date range.
How do I filter all the objects that ...
311
votes
6
answers
359k
views
Django values_list vs values
In Django, what's the difference between the following two:
Article.objects.values_list('comment_id', flat=True).distinct()
versus:
Article.objects.values('comment_id').distinct()
My goal is to get ...
284
votes
7
answers
273k
views
Checking for empty queryset in Django
What is the recommended idiom for checking whether a query returned any results?
Example:
orgs = Organisation.objects.filter(name__iexact = 'Fjuk inc')
# If any results
# Do this with the results ...
264
votes
2
answers
254k
views
">", "<", ">=" and "<=" don't work with "filter()" in Django
With = below, I could filter persons by age:
qs = Person.objects.filter(age = 20)
# ↑ Here
But with >, <, >= and <= below, I couldn't filter persons by age:
...
227
votes
8
answers
382k
views
How to select a record and update it, with a single queryset in Django?
How do I run an update and select statements on the same queryset rather than having to do two queries:
- one to select the object
- and one to update the object
The equivalent in SQL would be ...
224
votes
21
answers
298k
views
How can I filter a date of a DateTimeField in Django?
I am trying to filter a DateTimeField comparing with a date. I mean:
MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22))
I get an empty queryset list as an answer because (I think) I am ...
193
votes
4
answers
68k
views
aggregate() vs annotate() in Django
Django's QuerySet has two methods, annotate and aggregate. The documentation says that:
Unlike aggregate(), annotate() is not a terminal clause. The output of the annotate() clause is a QuerySet.
...
189
votes
3
answers
195k
views
Django - filtering on foreign key properties
I'm trying to filter a table in Django based on the value of a particular field of a ForeignKey.
For example, I have two models:
class Asset(models.Model):
name = models.TextField(max_length=150)...
185
votes
10
answers
253k
views
How to remove all of the data in a table using Django
I have two questions:
How do I delete a table in Django?
How do I remove all the data in the table?
This is my code, which is not successful:
Reporter.objects.delete()
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 ...
175
votes
14
answers
145k
views
.filter() vs .get() for single object? (Django)
I was having a debate on this with some colleagues. Is there a preferred way to retrieve an object in Django when you're expecting only one?
The two obvious ways are:
try:
obj = MyModel.objects....
163
votes
10
answers
191k
views
How to obtain a QuerySet of all rows, with specific fields for each one of them?
I have a model Employees and I would like to have a QuerySet of all rows, but with some specific fields from each row, and not all fields.
I know how to query all rows from the table/model:
Employees....
156
votes
4
answers
131k
views
How to do SELECT COUNT(*) GROUP BY and ORDER BY in Django?
I'm using a transaction model to keep track all the events going through the system
class Transaction(models.Model):
actor = models.ForeignKey(User, related_name="actor")
acted = models....
149
votes
3
answers
89k
views
Can a dictionary be passed to django models on create?
Is it possible to do something similar to this with a list, dictionary or something else?
data_dict = {
'title' : 'awesome title',
'body' : 'great body of text',
}
Model.objects.create(...
148
votes
7
answers
165k
views
Django: Calculate the Sum of the column values through query
I have a model:
class ItemPrice(models.Model):
price = models.DecimalField(max_digits=8, decimal_places=2)
# ...
I tried this to calculate the sum of price in this queryset:
items = ...
141
votes
4
answers
94k
views
How to show a many-to-many field with "list_display" in Django Admin?
class Product(models.Model):
products = models.CharField(max_length=256)
def __unicode__(self):
return self.products
class PurchaseOrder(models.Model):
product = models....
141
votes
9
answers
160k
views
Django filter queryset __in for *every* item in list
Let's say I have the following models
class Photo(models.Model):
tags = models.ManyToManyField(Tag)
class Tag(models.Model):
name = models.CharField(max_length=50)
In a view I have a list ...
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 ...
131
votes
7
answers
192k
views
Get the latest record with filter in Django
I am trying to get the latest Django model object but cannot seem to succeed.
Neither of these are working:
obj = Model.objects.filter(testfield=12).latest()
obj = Model.objects.latest().filter(...
130
votes
6
answers
116k
views
Count() vs len() on a Django QuerySet
In Django, given that I have a QuerySet that I am going to iterate over and print the results of, what is the best option for counting the objects? len(qs) or qs.count()?
(Also given that counting ...
126
votes
4
answers
45k
views
django - query filter on manytomany is empty
In Django is there a way to filter on a manytomany field being empty or null.
class TestModel(models.Model):
name = models.CharField(_('set name'), max_length=200)
manytomany = models....
122
votes
4
answers
77k
views
Django TypeError: 'RelatedManager' object is not iterable
I have these Django models:
class Group(models.Model):
name = models.CharField(max_length=100)
parent_group = models.ManyToManyField("self", blank=True)
def __unicode__(self)...
121
votes
4
answers
235k
views
Getting a count of objects in a queryset in Django
How can I add a field for the count of objects in a database. I have the following models:
class Item(models.Model):
name = models.CharField()
class Contest(models.Model);
name = models....
119
votes
13
answers
150k
views
Get last record in a queryset
How can I retrieve the last record in a certain queryset?
119
votes
6
answers
62k
views
django filter on the basis of text length
I would like to filter my model on the basis of the length of the text
Something like
MyModel.objects.filter(len(text) > 10)
where text is a Char or Text field in MyModel model
114
votes
10
answers
189k
views
How to output Django queryset as JSON?
I want to serialize my queryset, and I want it in a format as this view outputs:
class JSONListView(ListView):
queryset = Users.objects.all()
def get(self, request, *args, **kwargs):
...
112
votes
2
answers
142k
views
Django SUM Query?
I have a query akin to the following:
SELECT SUM(name) FROM table WHERE name IS NULL
How does that SUM translate into a QuerySet in Django? i.e. What operation xyz does it translate to, in something ...
108
votes
2
answers
47k
views
How to create a Django queryset filter comparing two date fields in the same model
Trying to get a query where the Activity record is stale in my Solr Index.
I want to check to see if the Activity.updated date in the database is greater than the Activity.added_toSolr_date for the ...
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....
97
votes
11
answers
50k
views
How to get primary keys of objects created using django bulk_create
Is there a way to get the primary keys of the items you have created using the bulk_create feature in django 1.4+?
94
votes
2
answers
81k
views
How to annotate Count with a condition in a Django queryset
Using Django ORM, can one do something like queryset.objects.annotate(Count('queryset_objects', gte=VALUE)). Catch my drift?
Here's a quick example to use for illustrating a possible answer:
In a ...
92
votes
5
answers
86k
views
Django Queryset with filtering on reverse foreign key
I have the following Django model:
class Make:
name = models.CharField(max_length=200)
class MakeContent:
make = models.ForeignKey(Make)
published = models.BooleanField()
I'd like to know ...
90
votes
2
answers
68k
views
Django: change the value of a field for all objects in a queryset
I have a model MyModel with a boolean field active
Elsewhere, I am retrieving a queryset:
qs = MyModel.Objects.filter(....)
how can I set active=False for all objects in this qs?
89
votes
4
answers
67k
views
'RelatedManager' object is not iterable Django
Hey i have looked around through some simliar posts here on SO but havent found anything that has solved my problem. I have the following models,
from django.db import models
class Areas(models....
89
votes
5
answers
27k
views
Django filter the model on ManyToMany count?
Suppose I have something like this in my models.py:
class Hipster(models.Model):
name = CharField(max_length=50)
class Party(models.Model):
organiser = models.ForeignKey()
participants = ...
87
votes
4
answers
76k
views
Django query datetime for objects older than 5 hours
I'm trying to write a Django query for widgets that are more than 5 hours old and I'm a bit lost. The widget model has a DateTimeField that is populated with the creation time of the widget.
85
votes
7
answers
25k
views
Django Query That Get Most Recent Objects From Different Categories
I have two models A and B. All B objects have a foreign key to an A object. Given a set of A objects, is there anyway to use the ORM to get a set of B objects containing the most recent object created ...
83
votes
3
answers
59k
views
Django Query __isnull=True or = None
this is a simple question. I'd like to know if it is the same to write:
queryset = Model.objects.filter(field=None)
than:
queryset = Model.objects.filter(field__isnull=True)
I'm using django 1.8
79
votes
3
answers
42k
views
Django Query Related Field Count
I've got an app where users create pages. I want to run a simple DB query that returns how many users have created more than 2 pages.
This is essentially what I want to do, but of course it's not the ...
79
votes
6
answers
57k
views
Django, query filtering from model method
I have these models:
def Foo(Models.model):
size = models.IntegerField()
# other fields
def is_active(self):
if check_condition:
return True
else:
...
78
votes
8
answers
55k
views
Custom QuerySet and Manager without breaking DRY?
I'm trying to find a way to implement both a custom QuerySet and a custom Manager without breaking DRY. This is what I have so far:
class MyInquiryManager(models.Manager):
def for_user(self, ...