Login

Tag "queryset"

Snippet List

Batch querysets

Most of the time when I need to iterate over Whatever.objects.all() in a shell script, my machine promptly reminds me that sometimes even 4GB isn't enough memory to prevent swapping like a mad man, and bringing my laptop to a crawl. I've written 10 bazillion versions of this code. Never again. **Caveats** Note that you'll want to order the queryset, as ordering is not guaranteed by the database and you might end up iterating over some items twice, and some not at all. Also, if your database is being written to in between the time you start and finish your script, you might miss some items or process them twice.

  • queryset
  • batch
Read More

Chain multiple querysets into one

This class acts as a wrapper around multiple querysets. Use it if you want to chain multiple QSs together without combining them with | or &. eg., to put title matches ahead of body matches: >>> qs1 = Event.objects.filter(## title matches ##) >>> qs2 = Event.objects.filter(## matches in other fields ##) >>> qs = MultiQuerySet(qs1, qs2) >>> len(qs) >>> paginator = Paginator(qs) >>> first_ten = qs[:10] It effectively acts as an immutable, sliceable QuerySet (with only a very limited subset of the QuerySet api)

  • queryset
  • chain
  • multi
Read More

ParentModel and ChildManager for Model Inheritance

This is the approach I've taken to access instances of child models from their parent. Functionally it's very similar to snippets [1031](http://www.djangosnippets.org/snippets/1031/) and [1034](http://www.djangosnippets.org/snippets/1034/), but without the use of `django.contrib.contenttypes`. Usage: class Post(ParentModel): title = models.CharField(max_length=50) objects = models.Manager() children = ChildManager() def __unicode__(self): return self.title def get_parent_model(self): return Post class Article(Post): text = models.TextField() class Photo(Post): image = models.ImageField(upload_to='photos/') class Link(Post): url = models.URLField() In this case, the `Post.children` manager will return a queryset containing instances of the appropriate child model, rather than instances of `Post`. >>> Post.objects.all() [<Post: Django>, <Post: Make a Tumblelog>, <Post: Self Portrait>] >>> Post.children.all() [<Link: Django>, <Article: Make a Tumblelog>, <Photo: Self Portrait>]

  • model
  • manager
  • queryset
  • inheritance
Read More

get_queryset_or_404

Sometimes we want to get a queryset or 404, for example, if we're passing our queryset to a subclassed generic view. This is identical to get_list_or_404 but returns a queryset.

  • shortcut
  • template
  • queryset
  • get_queryset_or_404
  • get_list_or_404
Read More

Custom managers with chainable filters

The Django docs show us how to give models a custom manager. Unfortunately, filter methods defined this way cannot be chained to each other or to standard queryset filters. Try it: class NewsManager(models.Manager): def live(self): return self.filter(state='published') def interesting(self): return self.filter(interesting=True) >>> NewsManager().live().interesting() AttributeError: '_QuerySet' object has no attribute 'interesting' So, instead of adding our new filters to the custom manager, we add them to a custom queryset. But we still want to be able to access them as methods of the manager. We could add stub methods on the manager for each new filter, calling the corresponding method on the queryset - but that would be a blatant DRY violation. A custom `__getattr__` method on the manager takes care of that problem. And now we can do: >>> NewsManager().live().interesting() [<NewsItem: ...>]

  • manager
  • queryset
Read More

Case-insensitive lookup by default

I wanted lookups on tags to be case insensitive by default, so that things like Tag.objects.get(name='Tag') would return any similar tags (ignoring case differences), i.e. `<Tag: tag>`. This snippet makes lookup on the 'name' field case-insensitive by default, although case-sensitive lookups can still be achieved with 'name__exact'. Methods like get_or_create will work as expected and be case-insensitive.

  • model
  • tags
  • tagging
  • manager
  • case-insensitive
  • iexact
  • queryset
Read More

39 snippets posted so far.