django-queryset

Django ORM: Retrieving posts and latest comments without performing N+1 queries

无人久伴 提交于 2019-12-06 03:54:27
问题 I have a very standard, basic social application -- with status updates (i.e., posts), and multiple comments per post. Given the following simplified models, is it possible, using Django's ORM, to efficiently retrieve all posts and the latest two comments associated with each post, without performing N+1 queries? (That is, without performing a separate query to get the latest comments for each post on the page.) class Post(models.Model): title = models.CharField(max_length=255) text = models

django distinct and order_by

自闭症网瘾萝莉.ら 提交于 2019-12-06 03:46:24
Foo.objects.all().distinct('foo') won't remove duplicates Foo.objects.all().order_by().distinct('foo') does remove them. I have Meta.ordering = ('-field1', '-field2) Does Foo.objects.all().order_by().distinct('foo') respects the Meta.ordering? i.e. I want distinct values ordered by Meta.ordering and not sure how to do it. Django Documentation is confusing and don't address how order_by() without any argument works. I'm using postgresql 9.3 btw. In [28]: BestMomsdiaryThread.objects.all().values_list('momsdiary_thread__id', flat=True) Out[28]: [3390, 5877, 5884, 6573, 5880, 6576, 6576, 6576,

Django pagination is repeating results

我怕爱的太早我们不能终老 提交于 2019-12-06 01:47:19
问题 I have this weird pagination bug in Django: using object_list as a return of a view, but passing a "paginate_by" argument to it, it's repeating some of the results; Otherwise, if I remove the argument or set as "paginate_by=None", the results are correct. If using pagination, the quantity of results is maintained at a total, so, because there are repeated results, the last results are left out of the list, so they don't appear in the template. Any ideas of what might be happening? Thanks! 回答1

Django Admin, can't groupe by: Exception Value: 'dict' object has no attribute '_meta'

送分小仙女□ 提交于 2019-12-06 01:15:20
I have this model which maps to a postgresql view class AppModel(models.Model): nbr = models.BigIntegerField(blank=True, null=True) region = models.ForeignKey(AppWilaya,blank=True, null=True) date_preorder = models.DateField(blank=True, null=True) id = models.IntegerField(primary_key=True,blank=True, db_column='dummy_id') What I want to achieve is to sum "nbr" by "region" , so: class AppModelAdmin(admin.ModelAdmin): .... def queryset(self, request): qs = super(AppModelAdmin, self).get_queryset(request) qs=qs.values("region").annotate(total=Sum( 'nbr')) But Django Admin seems not accepting

Django query for many-to-many subset containment

て烟熏妆下的殇ゞ 提交于 2019-12-05 23:17:38
问题 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)

Django count group by date from datetime

左心房为你撑大大i 提交于 2019-12-05 22:49:46
I'm trying to count the dates users register from a DateTime field. In the database this is stored as '2016-10-31 20:49:38' but I'm only interested in the date '2016-10-31'. The raw SQL query is: select DATE(registered_at) registered_date,count(registered_at) from User where course='Course 1' group by registered_date; It is possible using 'extra' but I've read this is deprecated and should not be done. It works like this though: User.objects.all() .filter(course='Course 1') .extra(select={'registered_date': "DATE(registered_at)"}) .values('registered_date') .annotate(**{'total': Count(

Is there an OR filter? - Django

◇◆丶佛笑我妖孽 提交于 2019-12-05 22:40:46
is there any way of doing the following Unicorn.objects.or_filter(magical=True).or_filter(unicorn_length=15).or_filter(skin_color='White').or_filter(skin_color='Blue') where or_filter stands for an isolated match I remember using something similar but cannot find the function anymore! Help would be great! Thanks :) You're looking for Q objects . 来源: https://stackoverflow.com/questions/2964540/is-there-an-or-filter-django

Can i sort query set return objects in order to function result

核能气质少年 提交于 2019-12-05 19:43:19
I am writing a web based music application and I want implement some feature that user can see most favor album in last week-month-year. so this is my model : class album(models.Model): def get_weely_count(): ... def get_monthly_count(): ... def get_yearly_count(): ... class like(models.Model): created_at = models.DateField() albumID = models.ForeignKey(Album) Now I want to receive albums that most liked in last week or last month or last year,I want done some thing like this(but I can not): Album.objects.all().order_by('get_weekly_count') can any one help me to fix it or give another approach

Django queryset aggregate by time interval

大城市里の小女人 提交于 2019-12-05 18:36:42
Hi I am writing a Django view which ouputs data for graphing on the client side (High Charts). The data is climate data with a given parameter recorded once per day. My query is this: format = '%Y-%m-%d' sd = datetime.datetime.strptime(startdate, format) ed = datetime.datetime.strptime(enddate, format) data = Climate.objects.filter(recorded_on__range = (sd, ed)).order_by('recorded_on') Now, as the range is increased the dataset obviously gets larger and this does not present well on the graph (aside from slowing things down considerably). Is there an way to group my data as averages in time

Single django queryset to get n adjacent items

可紊 提交于 2019-12-05 18:24:45
I'm making an "infinite"/continuous scrolling list (like twitter) and want to be able to navigate to a specific item. Finding the item is straight forward, but I need to get a few items before and after it. I'm using a similar approach to the answers suggested here: Getting next and previous objects in Django before = list(reversed(models.MyModel.objects.filter(pk__lt=pk).order_by('-pk')[:10])) after = list(models.MyModel.objects.filter(pk__gte=pk).order_by('pk')[:11]) objects = before + after Is there any way to combine these into the one query? I can't simply combine the two with the |