django-orm

How does determining subclass through hasattr trigger a db query in django's orm?

ぐ巨炮叔叔 提交于 2019-12-13 05:54:31
问题 For example, I am using multi-table inheritance for a class Node with sub-classes ConceptNode and DerivedNode. To determine the type of Node I am dealing with and distribute a function call down to the appropriate subclass, I often have to call hasattr like this: test_node = Node.objects.all()[0] if hasattr( test_node, "conceptnode"): test_node.conceptnode.myFunction() elif hasattr( test_node, "derivednode"): test_node.derivednode.myFunction() else: raise Exception("Not a valid type.") I've

Subquery in django ORM

佐手、 提交于 2019-12-13 05:27:31
问题 I have a table with next columns: key time value And I need to have a query like that: SELECT "time", SUM("value") FROM ( SELECT "key", django_trunc_datetime("time"), AVG("value") FROM my_table GROUP BY "key", django_trunc_datetime("time") ) GROUP BY "time" Is it possible in Django ORM? Maybe with some fake model based on the subquery? Thanks UPDATED: Looks like I have to create five database views (because there are Hour/Day/Week/Month/Year arguments for the django_trunc_datetime) but it can

Django Distinct and Foreign Key filtering Query

放肆的年华 提交于 2019-12-13 03:31:45
问题 I found questions about this problem but no working answer, so any help is appreciated :) I want to display a list of the lastest Record made by each Client. Records is a model, which has Client as a field. Client is a ForeignKey for User. For example #Initially: Client3 --- Record6 Client2 --- Record5 Client2 --- Record4 Client1 --- Record3 Client1 --- Record2 Client1 --- Record1 #Wanted: we only keep one Record per Client, the lastest one. Client3 --- Record6 Client2 --- Record5 Client1 ---

Aggregation of an expression in Django query spanning multiple tables

大城市里の小女人 提交于 2019-12-13 02:35:12
问题 Is it possible to compute an aggregation (ex.: sum) of an expression (ex.: subtraction) of fields from a related table in a Django ORM query? For a full example of what I'm trying to achieve, see this working SQL Fiddle. I broke it down into two questions (other one here). In this case, I have a model Sequence that represents a sequence of numbers, and a model Part that represent a "link" in this sequence: Sequence Sequence Sequence Sequence ... 0 5 20 15 ... |-- Part --|-- Part --|-- Part --

Django annotate a field value to queryset

女生的网名这么多〃 提交于 2019-12-13 01:23:02
问题 I want to attach a field value (id) to a QS like below, but Django throws a 'str' object has no attribute 'lookup' error. Book.objects.all().annotate(some_id='somerelation__id') It seems I can get my id value using Sum() Book.objects.all().annotate(something=Sum('somerelation__id')) I'm wondering is there not a way to simply annotate raw field values to a QS? Using sum() in this case doesn't feel right. 回答1: There are at least three methods of accessing related objects in a queryset. using

Django: m2m_changed not fired when end of relation is deleted

岁酱吖の 提交于 2019-12-12 22:02:38
问题 NOTICE : due to production environment constraints, I must stick to django-1.4 for the moment. I've just made a test to see whether I can hook onto an event when ManyToMany changes. I have a Group model that holds several Item objects. Whenever the items change in any group, I want to do something with concerned Group` instances. from django.db import models from django.db.models.signals import m2m_changed, post_delete, pre_delete class Item(models.Model): name = models.CharField(max_length

Django generate group by different than id

狂风中的少年 提交于 2019-12-12 21:16:14
问题 I want to count amount of Users for same Product models.py class Product(models.Model): pass class User(models.Model): product = models.ForeignKey(Product) age = models.IntegerField(blank=True, null=True) User.objects.filter(age__gt=18).annotate(product_count=Count('product_id')) output sql SELECT "user"."product_id" COUNT("user"."product_id") AS "product_count" FROM "user" WHERE "user"."age" > 18 GROUP BY "user"."id"; desired sql : SELECT "user"."product_id" COUNT("user"."product_id") AS

Django ORM with date_trunk function and timezones

半世苍凉 提交于 2019-12-12 10:44:33
问题 I would like to use date_trunc SQL function but it it doesn't seem to work with timezones. Test 1 with Django : from django.db import connection cursor = connection.cursor() cursor.execute(""" SELECT (date_trunc('day', when_start)) AS "d", COUNT("stats_histo_call"."id") AS "agg" FROM "stats_histo_call" WHERE ("stats_histo_call"."offre_id" = 28 AND "stats_histo_call"."when_start" BETWEEN '2014-08-04 00:00:00+02:00' and '2014-08-08 23:59:59.999999+02:00') GROUP BY (date_trunc('day', when_start)

Can we do a Sum on CharField in Django ORM?

邮差的信 提交于 2019-12-12 09:41:49
问题 My model in Django ORM is this class Test(Modelbase): id = models.IntegerField(null=True, blank=True) amount = models.CharField(max_length=255) I want to add the amount for list of id's. The only problem is the amount field is CharField . How do I apply sum for the amount field? Test.objects.filter(id__in=[1,2,3]).aggregate(Sum('amount')) I am using Django=1.9.1 for this. 回答1: you can try do annotate with cast: from django.db.models import FloatField from django.db.models.functions import

Django spanning relationships

霸气de小男生 提交于 2019-12-12 08:53:38
问题 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