#35587: Add QuerySet.partition(*args, **kwargs)
-------------------------------------+-------------------------------------
     Reporter:  micahcantor          |                     Type:  New
                                     |  feature
       Status:  new                  |                Component:  Database
                                     |  layer (models, ORM)
      Version:  5.0                  |                 Severity:  Normal
     Keywords:                       |             Triage Stage:
                                     |  Unreviewed
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------
 A common task with a Django model is to partition the model instances into
 two sets, ones that is selected by some filters, and ones that are not.
 Naively, the following utility script can accomplish this with
 QuerySet.filter() and QuerySet.exclude()

 {{{
 from django.db.models import QuerySet
 from django.db.models.manager import BaseManager

 def partition(self, *args, **kwargs):
     filtered = self.filter(*args, **kwargs)
     excluded = self.exclude(*args, **kwargs)
     return filtered, excluded

 QuerySet.partition = partition
 BaseManager.partition = partition
 }}}

 For instance, if we have a Book model, we can divide it into those that
 are fiction and nonfiction.

 {{{
 fiction, nonfiction = Book.objects.partition(genre="fiction")
 }}}

 Obtaining two separate QuerySets is often helpful if we want add further
 filters, ordering, or prefetches to one set but not the other.

 Adding this method to Django would be a helpful utility, and could also be
 implemented more efficiently than my own naive implementation. It would be
 difficult for me to suggest a better implementation without a deeper
 understanding of the implementations of filter() and exclude().
-- 
Ticket URL: <https://code.djangoproject.com/ticket/35587>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/010701909941d9a1-44a09e49-e7c4-426a-93e7-aa90bf5e67ab-000000%40eu-central-1.amazonses.com.

Reply via email to