django-orm

Django: Sum on an date attribute grouped by month/year

心已入冬 提交于 2019-12-04 08:38:28
I'd like to put this query from SQL to Django: "select date_format(date, '%Y-%m') as month, sum(quantity) as hours from hourentries group by date_format(date, '%Y-%m') order by date;" The part that causes problem is to group by month when aggregating. I tried this (which seemed logical), but it didn't work : HourEntries.objects.order_by("date").values("date__month").aggregate(Sum("quantity")) aggregate can only generate one aggregate value. You can get the aggregate sum of Hours of the current month by the following query. from datetime import datetime this_month = datetime.now().month

Django database query: How to get object by id?

谁都会走 提交于 2019-12-04 07:48:52
问题 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? 回答1: If you want to get an object, using get() is more straightforward: obj = Class.objects.get(pk=this_object_id) 回答2: I got here for the same problem, but for a different reason: Class.objects.get(id=1) This code was raising an ImportError exception. What was confusing me was that the code below executed fine and returned a result set as

Can I control the GROUP BY in django 1.3's orm?

痴心易碎 提交于 2019-12-04 07:48:42
I think this will best be explained with an example. Here is what the data would looks like: |project | |id|name | |1 |some project | |2 |my other project| |run | |id|project_id|start_time |result | |1 |1 |1305732581845|something| |2 |1 |1305732593721|nothing | |3 |2 |1305732343721|nothing | |4 |2 |1305732556821|something| I would like to be able to get an entire recordset from each of the latest runs by project. The SQL Query would look something like this: SELECT *, MAX("run"."start_time") FROM "run" LEFT OUTER JOIN "project" ON ("run"."project_id" = "project"."id") GROUP BY "project"."id"

Django spanning relationships

无人久伴 提交于 2019-12-04 05:42:45
I've read the documentation but am still coming up with errors. I have Users placing Orders for Catalog objects. I'd like to create a query which returns all Users that have an Order containing a specific Catalog item. Here are my models: class Catalog(models.Model): name = models.CharField(max_length=100) price = models.IntegerField() def __unicode__(self): return self.name class Annual(models.Model): catalog = models.OneToOneField(Catalog, blank=True, null=True, related_name='annual_products') year_id = models.IntegerField(max_length=4) start_date = models.CharField(max_length=10) end_date =

Django performance testing suite that'll report on metrics (db queries etc.)

梦想的初衷 提交于 2019-12-04 05:36:58
I have a complex Django web application that has many person-years of work put into it. It might need optimisation sometime. There are several common operation/flows that I could script with (say) django's test client. Is there some programme that, given a python script like that, will run then, and report on various django specific performance metrics, like 'number of sql queries run'. Essentially something like a unittest test suite, but rather than reporting "0 tests failed", it'd report "X db queries were made" I could write this myself, it's not exactly a complex problem, but I wonder has

Reverse Queryset Order in Django [duplicate]

ぐ巨炮叔叔 提交于 2019-12-04 03:52:50
问题 This question already has an answer here : How can I tell the Django ORM to reverse the order of query results? (1 answer) Closed 4 years ago . Is there any simple way to reverse the order of a queryset in Django? Example: li = [1, 2, 3] queryset = Collection.objects.filter(pk__in=li) 回答1: You can use queryset = reversed(Collection.objects.filter(pk__in = li)) or queryset = Collection.objects.filter(pk__in = li).reverse() 回答2: To reverse qs queryset = Collection.objects.filter(pk__in = li)

Django query for many-to-many subset containment

跟風遠走 提交于 2019-12-04 03:20:30
Is there a way to query for subset or superset containment with many-to-many fields? Suppose each Person has a list of birds they want to see, and each Aviary houses a list of birds. How can I make a query to find, for a given Person instance, which Aviaries have every bird on the person's list? And similarly, for a given Person instance, how do I find which Aviaries have only birds on the person's list (but not necessarily all of them). Here are my Django 1.5 models: class Bird(models.Model): name = models.CharField(max_length=255, unique=True) class Aviary(models.Model): name = models

how to get list of objects involving many to many relation in django

别等时光非礼了梦想. 提交于 2019-12-04 02:08:33
I have the following models: class Committee(models.Model): customer = models.ForeignKey(Customer, related_name="committees") name = models.CharField(max_length=255) members = models.ManyToManyField(member, through=CommitteeMember, related_name="committees") items = models.ManyToManyField(Item, related_name="committees", blank=True) class CommitteeRole(models.Model): committee = models.ForeignKey('Committee') member = models.ForeignKey(member) #user is the members user/user number user = models.ForeignKey(User) role = models.IntegerField(choices=ROLES, default=0) class Member(models.Model):

Django order items by two fields, but ignoring them if they're zero

早过忘川 提交于 2019-12-04 00:50:03
I have the following model (greatly simplified for the purposes of this question): class Product(models.Model): price = models.DecimalField(max_digits=8, decimal_places=2) sale_price = models.DecimalField(max_digits=10, blank=True, null=True, decimal_places=2) For the majority of products, price will be filled but sale_price will not be. So, I can order products by price like so: Product.objects.order_by('price') Product.objects.order_by('-price') However, some products will have a sale_price, and I can't find a way to order these neatly so that the sale price interleaves with the normal price

Django N+1 query solution

匆匆过客 提交于 2019-12-04 00:18:49
I visited http://guides.rubyonrails.org/active_record_querying.html after talking with a peer regarding N+1 and the serious performance implications of bad DB queries. ActiveRecord (Rails): clients = Client.includes(:address).limit(10) Where client's have addresses, and I intend to access them while looping through the clients, Rails provides includes to let it know to go ahead and add them to the query, which eliminates 9 queries right off the bat. Django: https://github.com/lilspikey/django-batch-select provides batch query support. Do you know of other libraries or tricks to achieve what