django-queryset

Annotate a queryset with the average date difference? (django)

随声附和 提交于 2019-12-04 18:00:04
问题 I searched all over place for an answer to this but couldn't find anything. Perhaps this is just a stupid question or a really tricky one. Here it is: Let's say my model is this (pseudo django code): Event type = ForeignKey(EventType) name = CharField date_start = DateField date_end = DateField EventType name = CharField What I want to know is the average duration time for each event type. What I do now is calculate the average duration whenever a new event is created (save method) and have

Django QuerySet vs Raw Query performance

陌路散爱 提交于 2019-12-04 17:39:31
I have noticed a huge timing difference between using django connection.cursor vs using the model interface, even with small querysets. I have made the model interface as efficient as possible, with values_list so no objects are constructed and such. Below are the two functions tested, don't mind the spanish names. def t3(): q = "select id, numerosDisponibles FROM samibackend_eventoagendado LIMIT 1000" with connection.cursor() as c: c.execute(q) return list(c) def t4(): return list(EventoAgendado.objects.all().values_list('id','numerosDisponibles')[:1000]) Then using a function to time (self

Two or more __in filters in django queryset

妖精的绣舞 提交于 2019-12-04 15:19:30
I have this query query = 'select * from products where (productnr, supplier_id) in (%s)' % product_list where product_list looks like this ((OB520, 3),(RH402, 20)...) How do I go about doing this in Django using queryset and the __in filter What part of this is confusing? http://docs.djangoproject.com/en/1.2/ref/models/querysets/#in It seems very clear. It's not perfectly clear from the question what the problem is. Are you asking how to use a multi-part key? If so, you're going to be unhappy with simple __in . If you're trying to look for an "OR" of a two-part key, you have to create a more

django: time range based aggregate query

試著忘記壹切 提交于 2019-12-04 14:28:56
问题 I have the following models, Art and ArtScore: class Art(models.Model): title = models.CharField() class ArtScore(models.Model): art = models.ForeignKey(Art) date = models.DateField(auto_now_add = True) amount = models.IntegerField() Certain user actions results in an ArtScore entry, for instance whenever you click 'I like this art', I save a certain amount of ArtScore for that Art. Now I'm trying to show a page for 'most popular this week', so I need a query aggregating only ArtScore amounts

Django multiple queryset combine into a pagination

喜夏-厌秋 提交于 2019-12-04 13:55:49
I have combine 2 queryset from different models into a list and used pagination to display as a single list. The problem is the objects from the list are displayed by the pagination according to the models they were created from. How could I fix the list so when a new object is created from the models. It will be displayed after the recently created object even though the recent object created was from a different models. Example would be . I have a combine queryset of user's whiteboard and user's comment. If a new whiteboard 's object was created recently and I would create another comment .

Django Inline for ManyToMany generate duplicate queries

三世轮回 提交于 2019-12-04 12:53:11
I'm experiencing some major performing issue with my django admin. Lots of duplicate queries based on how many inlines that I have. models.py class Setting(models.Model): name = models.CharField(max_length=50, unique=True) class Meta: ordering = ('name',) def __str__(self): return self.name class DisplayedGroup(models.Model): name = models.CharField(max_length=30, unique=True) position = models.PositiveSmallIntegerField(default=100) class Meta: ordering = ('priority',) def __str__(self): return self.name class Machine(models.Model): name = models.CharField(max_length=20, unique=True) settings

Django Custom Queryset filters

荒凉一梦 提交于 2019-12-04 11:28:35
问题 Is there, in Django, a standard way to write complex, custom filters for QuerySets? Just as I can write MyClass.objects.all().filter(field=val) I'd like to do something like this : MyClass.objects.all().filter(customFilter) I could use a generator expression (x for x in MyClass.objects.all() if customFilter(x)) but that would lose the chainability and whatever other functions the QuerySets provide. 回答1: I think you may need custom managers. 回答2: The recommendation to start using manager

Django SQL query duplicated n times

﹥>﹥吖頭↗ 提交于 2019-12-04 11:11:53
问题 I have a book model and a rating model, class Book(models.Model): title = models.CharField(max_length=255) slug = AutoSlugField(unique=True, populate_from='title') description = models.TextField() # more fields class Rating(models.Model): book = models.ForeignKey('library.Book') score = models.DecimalField(max_digits=2, decimal_places=1) the Query, books = {'books': Book.objects.filter(pk__in=Rating.objects.all().order_by('-score' ).values_list('book__id', flat=True))[:10] } template, {% for

In Django, what is the most efficient way to check for an empty query set?

混江龙づ霸主 提交于 2019-12-04 10:12:55
问题 I've heard suggestions to use the following: if qs.exists(): ... if qs.count(): ... try: qs[0] except IndexError: ... Copied from comment below: "I'm looking for a statement like "In MySQL and PostgreSQL count() is faster for short queries, exists() is faster for long queries, and use QuerySet[0] when it's likely that you're going to need the first element and you want to check that it exists. However, when count() is faster it's only marginally faster so it's advisable to always use exists()

How to use subquery in django?

左心房为你撑大大i 提交于 2019-12-04 10:06:12
问题 I want to get a list of the latest purchase of each customer, sorted by the date. The following query does what I want except for the date: (Purchase.objects .all() .distinct('customer') .order_by('customer', '-date')) It produces a query like: SELECT DISTINCT ON "shop_purchase.customer_id" "shop_purchase.id" "shop_purchase.date" FROM "shop_purchase" ORDER BY "shop_purchase.customer_id" ASC, "shop_purchase.date" DESC; I am forced to use customer_id as the first ORDER BY expression because of