django-queryset

Caching queryset choices for ModelChoiceField or ModelMultipleChoiceField in a Django form

爷,独闯天下 提交于 2019-12-17 22:42:28
问题 When using ModelChoiceField or ModelMultipleChoiceField in a Django form, is there a way to pass in a cached set of choices? Currently, if I specify the choices via the queryset parameter, it results in a database hit. I'd like to cache these choices using memcached and prevent unnecessary hits to the database when displaying a form with such a field. 回答1: You can override "all" method in QuerySet something like from django.db import models class AllMethodCachingQueryset(models.query.QuerySet

How to sort by annotated Count() in a related model in Django

 ̄綄美尐妖づ 提交于 2019-12-17 22:23:59
问题 I'm building a food logging database in Django and I've got a query related problem. I've set up my models to include (among other things) a Food model connected to the User model through an M2M-field "consumer" via the Consumption model. The Food model describes food dishes and the Consumption model describes a user's consumption of Food (date, amount, etc). class Food(models.Model): food_name = models.CharField(max_length=30) consumer = models.ManyToManyField("User", through=Consumption)

How to do a less than or equal to filter in Django queryset?

回眸只為那壹抹淺笑 提交于 2019-12-17 22:08:12
问题 I am attempting to filter users by a custom field in each users profile called profile. This field is called level and is an integer between 0-3. If I filter using equals, I get a list of users with the chosen level as expected: user_list = User.objects.filter(userprofile__level = 0) When I try to filter using less than: user_list = User.objects.filter(userprofile__level < 3) I get the error: global name 'userprofile__level' is not defined Is there away to filter by < or >, or am I barking up

How to filter a django queryset using an array on a field like SQL's “IN”?

十年热恋 提交于 2019-12-17 19:08:11
问题 I'd like to filter a django queryset using an array as a constraint on a field. AKA, my array, for example, a set of primary keys. I want to get only the objects that would be in that array, like the query in SQL would be SELECT * from table where id in [1,3,4,5,6....]; 回答1: .filter(id__in=[1, 3, 4, 5, 6....]) Read more about it at Django docs. 来源: https://stackoverflow.com/questions/4016794/how-to-filter-a-django-queryset-using-an-array-on-a-field-like-sqls-in

Django: Does prefetch_related() follow reverse relationship lookup?

两盒软妹~` 提交于 2019-12-17 15:36:14
问题 I've tried prefetch_related() in django 1.4 from trunk and can't make it to prefetch reverse lookup. My simplified models (each book has many prices): class Book(models.Model): # some fields class Price(models.Model): book = models.ForeignKey(Book) My view's query: books = Book.objects.prefetch_related('price') Then, I got the AttributeError message: AttributeError: Cannot find 'price' on Book object, 'price' is an invalid parameter to prefetch_related() How to make it work? Thanks. 回答1:

Get the latest record with filter in Django

你说的曾经没有我的故事 提交于 2019-12-17 15:28:02
问题 I am trying to get the latest Django model object but cannot seem to succeed. Neither of these are working: obj = Model.objects.filter(testfield=12).latest() obj = Model.objects.latest().filter(testfield=12) 回答1: obj= Model.objects.filter(testfield=12).order_by('-id')[0] 回答2: See the docs from django: https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest You need to specify a field in latest(). eg. obj= Model.objects.filter(testfield=12).latest('testfield') Or if your model’s

Django: ManyToMany filter matching on ALL items in a list

梦想的初衷 提交于 2019-12-17 09:49:53
问题 I have such a Book model: class Book(models.Model): authors = models.ManyToManyField(Author, ...) ... In short: I'd like to retrieve the books whose authors are strictly equal to a given set of authors. I'm not sure if there is a single query that does it, but any suggestions will be helpful. In long: Here is what I tried, (that failed to run getting an AttributeError) # A sample set of authors target_authors = set((author_1, author_2)) # To reduce the search space, # first retrieve those

How to order a queryset by related objects count?

老子叫甜甜 提交于 2019-12-14 02:44:03
问题 My models.py is currently set up as follows: class Topic(models.Model): topic = models.CharField(max_length = 50) def __str__(self): return self.topic class Comic(models.Model): ... topic = models.ForeignKey(Topic, blank = True, null = True, related_name = 'comics') Anyway, from this its understandable that 2 comics can share the same topic, however, each comic can only have one topic. Now I need a list of objects of the Topic model ordered according to the number of Comic objects associated

Django Queryset absolute value of the annotated field

此生再无相见时 提交于 2019-12-14 01:17:43
问题 How do I get the absolute value of the annotated field? I tried the code below but it did't work. queryset.annotate(relevance=abs(F('capacity') - int( request.GET['capacity']) ) ).order_by('relevance') Error: TypeError: bad operand type for abs(): 'CombinedExpression' Thanks in advance! 回答1: You can try with func expressions: from django.db.models import Func, F queryset.annotate(relevance=Func(F('capacity') - int(request.GET['capacity']), function='ABS')) 来源: https://stackoverflow.com

Querying for followers in news-feed-based data model in Django

白昼怎懂夜的黑 提交于 2019-12-13 21:21:30
问题 I have this following (simplified) model in Django which is very similar to the Pinterest data model: class UserProfile(models.Model): user = models.OneToOneField(User) class Collection(models.Model): owner = models.ForeignKey(User,related_name='collection_owner') followers = models.ManyToManyField(User, related_name='collection_followers', null=True, blank=True, default = None) class Item(models.Model): collections = models.ManyToManyField(Collection,blank=True,null=True) I have a User model