django-queryset

django - reorder queryset after slicing it

﹥>﹥吖頭↗ 提交于 2019-12-21 04:34:32
问题 I fetch the latest 5 rows from a Foo model which is ordered by a datetime field. qs = Foo.objects.all()[:5] In the following step, I want to reorder the queryset by some other criteria (actually, by the same datetime field in the opposite direction). But reordering after a slice is not permitted. reverse() undoes the first ordering, giving me a differet queryset. Is there a way to accomplish what I want without creating a list from the queryset and doing the ordering using it? 回答1: No, there

Django select_related filter

女生的网名这么多〃 提交于 2019-12-21 03:42:05
问题 I have the following Django models. class A(models.Model): tmp = models.ForeignKey(B) active = models.BooleanField() class B(models.Model): active = models.BooleanField() archived = models.BooleanField() Now I have the following query. A.objects.select_related(B).filter(active=True) Now this fetches all the objects of B. Now how can I include a filter of active=True and archived=False in the select_related clause for model B . 回答1: The same as you would with any other related field, with a __

Generate a django queryset based on dict keys

倾然丶 夕夏残阳落幕 提交于 2019-12-21 02:57:07
问题 I have a dict like: { 'key1' : val1, 'key2' : val2 } And I need a queryset like Q(key1__icontains = val1) | Q(key2__icontains = val2) Thanks 回答1: reduce(operator.or_, Q(**{key + '__icontains': val}) for (key, val) in D.iteritems()) 回答2: There's a more pragmatic approach, as I need to generate various keys from one. query = None for key, value in d.iteritems(): if query is None: query = Q(**{key + "__icontains" : value}) else: query |= Q(**{key + "__icontains" : value}) 来源: https:/

How can I get previous and next objects from a filtered, ordered queryset?

无人久伴 提交于 2019-12-21 02:23:19
问题 I have a page based on a model object, and I want to have links to the previous and next pages. I don't like my current solution because it requires evaluating the entire queryset (to get the ids list), and then two more get queries. Surely there is some way this can be done in one pass? def get_prev_and_next_page(current_page): ids = list(Page.objects.values_list("id", flat=True)) current_idx = ids.index(current_page.id) prev_page = Page.objects.get(id=ids[current_idx-1]) try: next_page =

Calling filter with a variable for field name

半城伤御伤魂 提交于 2019-12-20 11:15:08
问题 Is there a way to call filter on a queryset where one of the fieldnames is a variable? For example I have something like: models.py class Playlist(models.Model): video = ... views.py field_name = 'video' Playlist.objects.filter(field_name=v) Which of course results in an error that field_name is not an attribute upon which Playlist can be filtered. 回答1: Playlist.objects.filter(**{field_name: v}) 回答2: To use field name string with icontains . Try this field_name = 'video' field_name_icontains

Django filter queryset on “tuples” of values for multiple columns

余生颓废 提交于 2019-12-20 10:29:09
问题 Say I have a model: Class Person(models.Model): firstname = models.CharField() lastname = models.CharField() birthday = models.DateField() # etc... and say I have a list of 2 first names: first_list = ['Bob', 'Rob'] And I have a list of 2 last names: last_list = ['Williams', 'Williamson'] . Then if I wanted to select everyone whose first name was in first_list I could run: Person.objects.filter(firstname__in=first_list) and if I wanted to select everyone whose last name was in last_list , I

django annotate and count: how to filter the ones to include in count

放肆的年华 提交于 2019-12-20 09:05:59
问题 Given a queryset, I add the count of related objects (ModelA) with the following: qs = User.objets.all() qs.annotate(modela__count=models.Count('modela')) However, is there a way to count the ModelA that only meet a criteria? For example, count the ModelA where deleted_at is null? I have tried two solutions which do not properly work. 1) As @knbk suggested, use filter before you annotate. qs = User.objects.all().filter(modela__deleted_at__isnull=True).annotate(modela__count=models.Count(

Django query annotation with boolean field

爱⌒轻易说出口 提交于 2019-12-20 08:59:11
问题 Let's say I have a Product model with products in a storefront, and a ProductImages table with images of the product, which can have zero or more images. Here's a simplified example: class Product(models.Model): product_name = models.CharField(max_length=255) # ... class ProductImage(models.Model): product = models.ForeignKey(Product, related_name='images') image_file = models.CharField(max_length=255) # ... When displaying search results for products, I want to prioritize products which have

Django concatenate two querysets for same model

你离开我真会死。 提交于 2019-12-20 02:41:39
问题 I have a list of Products , each belonging to a different Distributor . I need to display a form for each of those products and their corresponding distributor. I can do so with this code: form_products = ProductFormSet( queryset = Product.objects.filter(product__id=product_id) ) The problem is that I need to display the form with the product belonging to a particular Distributor named "FirstDistributor" first in the page. I tried to do so with the following code using the | operator between

Is there a way to augment django QuerySets with extra attributes?

末鹿安然 提交于 2019-12-19 10:02:26
问题 I'm trying to add some extra attributes to the elements of a QuerySet so I can use the extra information in templates, instead of hitting the database multiple times. Let me illustrate by example, assuming we have Books with ForeignKeys to Authors. >>> books = Book.objects.filter(author__id=1) >>> for book in books: ... book.price = 2 # "price" is not defined in the Book model >>> # Check I can get back the extra information (this works in templates too): >>> books[0].price 2 >>> # but it's