django-queryset

How to prefetch_related in reverse of a Django ManyToMany field

懵懂的女人 提交于 2020-01-06 06:44:25
问题 In Django, if I have a ManyToManyField: class Topping(models.Model): name = models.CharField(max_length=30) class Pizza(models.Model): name = models.CharField(max_length=50) toppings = models.ManyToManyField(Topping) I can minimize hits on the database when accessing the Pizza model's toppings field by using prefetch_related(): Pizza.objects.all().prefetch_related('toppings') How can I do the same but in reverse, to prefetch the pizza_set from a Topping queryset? This doesn't work, and I

Specifying order_by on Related Field in Django

我的未来我决定 提交于 2020-01-05 19:17:59
问题 In Django, on a given model it looks like the RelatedManager may only be set statically (see: docs) but is there any way to set the order_by on the related manager for a given Queryset? I tried using prefetch_related and Prefetch , but that does not seem to work: qs = qs.prefetch_related( Prefetch('item_set', queryset=Item.objects.order_by('capture_dt').all())) res = qs.first().item_set.all().ordered In this case res is False . The problem comes when I try to access the related manager:

Django filter query - doesn't work

不羁的心 提交于 2020-01-05 08:43:26
问题 I have problems with my Django, I want to write a very simple query but it doesn't work. Model: class Games(models.Model): name = models.CharField(max_length=128) path_to_folder = models.CharField(max_length=256) description = models.TextField() cover = models.URLField() def __str__(self): return self.name I am trying something like this (It should find itself in my opinion): >>> from gamepanel.models import Games >>> e = Games.objects.all() >>> print (e) [<Games: Call Of Duty 4>] >>> e[0]

Sum computed column in Django QuerySet

拜拜、爱过 提交于 2020-01-04 14:29:09
问题 Given the following Contribution model: class Contribution(models.Model): start_time = models.DateTimeField() end_time = models.DateTimeField(null=True) is it possible, using the Django database API, to reproduce the following SQL statement? SELECT SUM(end_time - start_time) AS total_duration FROM contribution; I've figured out this much: Contribution.objects.aggregate(total_duration=models.Sum( ??? )) but I'm not sure about how to represent the end_time - start_time part. Thanks! 回答1: Not

Modify results of django queryset

耗尽温柔 提交于 2020-01-03 05:49:07
问题 I have two models Event and Shift . class Event(models.Model): start = models.DateTimeField() end = models.DateTimeField(blank=True, null=True) class Shift(models.Model): name = models.CharField(max_length=20) start = models.TimeField() end = models.TimeField() Now on some view I have to filter out Events that occur in the interval of a Shift . And I did this. queryset = Event.objects.all() queryset = queryset.filter(start__time__gte=s.start).filter(start__time__lte=s.end) |\ queryset.filter

get ids group by range django

瘦欲@ 提交于 2020-01-03 03:09:07
问题 I have: Model: id = PrimaryKey() value = IntegerField() I would like to get list of ids group by value range between 1-7 and 8-30 and >30 . What would be the efficient way to do so? Or shall I write query for each range like: one= Model.objects.filter(value__gt=0,value__lte=7).values_list(id) two= Model.objects.filter(value__gt=7,value__lte=30).values_list(id) three= Model.objects.filter(value__gt=30).values_list(id) ... can I do so via aggregate Count ? I want minimum database transactions.

Emulate filtering-by-property in Django, using property and queryset annotation

拜拜、爱过 提交于 2020-01-03 03:08:47
问题 Summary It appears we can create a property on a Django model, and add an annotation with the exact same name to querysets for that model. For example, our FooBarModel has foo = property(...) , and on top of that we can do FooBarModel.objects.annotate(foo=...) . Note that the names are the same: If foo were a normal attribute, instead of a property , annotate(foo=...) would raise a ValueError . In this case, no such error. Initial tests suggest this approach works, allowing us to create e.g.

How to create a conversation inbox in Django

老子叫甜甜 提交于 2020-01-02 17:18:40
问题 I have a Message class which has fromUser , toUser , text and createdAt fields. I want to imitate a whatsapp or iMessage or any SMS inbox, meaning I want to fetch the last message for each conversation. I tried: messages = Message.objects.order_by('createdAt').distinct('fromUser', 'toUser') But this doesn't work because of SELECT DISTINCT ON expressions must match initial ORDER BY expressions error. I don't really understand what it means, I also tried: messages = Message.objects.order_by(

Rewrite raw SQL as Django query

≯℡__Kan透↙ 提交于 2020-01-02 11:16:11
问题 I am trying to write this raw SQL query, info_model = list(InfoModel.objects.raw('SELECT *, max(date), count(postid) AS freq, count(DISTINCT author) AS contributors FROM crudapp_infomodel GROUP BY topicid ORDER BY date DESC')) as a django query. The following attempt does not work as I can't get related fields for 'author' and 'post'. info_model = InfoModel.objects.values('topic') .annotate( max=Max('date'), freq=Count('postid'), contributors=Count('author', distinct=True)) .order_by('-max')

How to write a Django QuerySet the properly computes average of DateTimeField with grouping?

跟風遠走 提交于 2020-01-02 10:02:54
问题 Here is my Django model: class MyModel(models.Model): a = IntegerField() b = DateTimeField() Here is the QuerySet I execute on this model to find the count, min, max and average b s for each value of a : >>> from django.db.models import Count, Max, Min, Avg >>> MyModel.objects.extra( ... select={'avg': 'AVG(UNIX_TIMESTAMP(b))'} ... ).values('a').annotate( ... count=Count('b'), ... min=Min('b'), ... max=Max('b'), ... ) Here is the result of the QuerySet above: [ {'a': 1, 'count': 5, 'min':