Questions tagged [django-queryset]

Django querysets are the primary abstraction for retrieving objects from Django's ORM system

Django querysets are the primary abstraction for retrieving objects from Django's ORM system using custom SQL queries. They abstract both the creation of queries as well as the assembly of the model objects that are returned.

See also

6784 questions
188
votes
4 answers

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…
182
votes
3 answers

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) project = models.ForeignKey('Project') class…
Fraser Graham
  • 4,650
  • 4
  • 22
  • 42
180
votes
10 answers

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()
zjm1126
  • 34,604
  • 53
  • 121
  • 166
170
votes
14 answers

.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.get(id=1) except MyModel.DoesNotExist: # We…
Cory
  • 22,772
  • 19
  • 94
  • 91
163
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 myfieldname FROM mytable (or alternatively) SELECT…
alj
  • 2,839
  • 5
  • 27
  • 37
158
votes
8 answers

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.objects.all() I would like to know how to select…
zentenk
  • 2,725
  • 6
  • 25
  • 31
148
votes
4 answers

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.ForeignKey(User, related_name="acted", null=True,…
totoromeow
  • 2,199
  • 4
  • 19
  • 19
147
votes
7 answers

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 = ItemPrice.objects.all().annotate(Sum('price')) What's…
Ahsan
  • 11,516
  • 12
  • 52
  • 79
146
votes
3 answers

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(data_dict) Even better if I can extend…
clarence
140
votes
9 answers

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 with active filters called categories. I want to…
Sander van Leeuwen
  • 2,963
  • 2
  • 22
  • 31
136
votes
4 answers

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.ManyToManyField('Product') vendor =…
Mdjon26
  • 2,145
  • 4
  • 19
  • 29
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 looks like: class ProductOrder(models.Model): …
jamida
  • 2,869
  • 5
  • 25
  • 22
129
votes
7 answers

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(testfield=12)
doniyor
  • 36,596
  • 57
  • 175
  • 260
127
votes
6 answers

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 the objects in the same iteration is not an option.)
antonagestam
  • 4,532
  • 3
  • 32
  • 44
125
votes
4 answers

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.ManyToManyField('AnotherModel', blank=True,…
John
  • 21,047
  • 43
  • 114
  • 155