Login

Tag "managers"

Snippet List

Tatsypie: additional list endpoints for custom Model's manager methods

Although configuring filtering in TastyPie is possible, it is limited to per-field filters, which are not enough for more complex filtering. If your model implement custom manager methods for complex filters, exposing these methods as TastyPie Resource list endpoints is not an easy task. The ModelResource subclass provided here does this, providing 3 ways of complex filtering: * define querysets for filters directly in the Resource declaration * use Model manager custom method * use QuerySet custom method

  • managers
  • manager
  • custom-manager
  • tastypie
Read More

Binding signals to abstract models

Intro ----- I found a question on SO for which Justin Lilly's answer was correct but not as thorough as I'd like, so I ended up working on a simple snippet that shows how to bind signals at runtime, which is nifty when you want to bind signals to an abstract class. Bonus: simple cache invalidation! Question -------- [How do I use Django signals with an abstract model?](http://stackoverflow.com/questions/2692551/how-do-i-use-django-signals-with-an-abstract-model) I have an abstract model that keeps an on-disk cache. When I delete the model, I need it to delete the cache. I want this to happen for every derived model as well. If I connect the signal specifying the abstract model, this does not propagate to the derived models: pre_delete.connect(clear_cache, sender=MyAbstractModel, weak=False) If I try to connect the signal in an init, where I can get the derived class name, it works, but I'm afraid it will attempt to clear the cache as many times as I've initialized a derived model, not just once. Where should I connect the signal? Answer ------ I've created a custom manager that binds a post_save signal to every child of a class, be it abstract or not. This is a one-off, poorly tested code, so beware! It works so far, though. In this example, we allow an abstract model to define CachedModelManager as a manager, which then extends basic caching functionality to the model and its children. It allows you to define a list of volatile keys that should be deleted upon every save (hence the post_save signal) and adds a couple of helper functions to generate cache keys, as well as retrieving, setting and deleting keys. This of course assumes you have a cache backend setup and working properly.

  • managers
  • models
  • cache
  • model
  • manager
  • signals
  • abstract
  • signal
  • contribute_to_class
Read More

Automatic Manager Choice Filters

Automatically adds filter methods to your objects manager based on their display name. class Foo(models.Model): MOO_CHOICES=((1,'foo'),(2,'bar')) moo = models.IntegerField(choices=MOO_CHOICES) objects = ChoiceFilterManager('moo',MOO_CHOICES) Foo.objects.foo() Foo.objects.bar()

  • managers
  • choices
Read More

Custom Django manager that excludes subclasses

When you're using Django model inheritance, sometimes you want to be able to get objects of the base class that aren't instances of any of the subclasses. You might expect the obvious way of doing this, `SuperModel.objects.filter(submodel__isnull=True)`, to work, but unfortunately it doesn't. (Neither does `SuperModel.objects.filter(submodel__supermodel_ptr=None)`, or any other convoluted way I could think of doing it.) Here's a nicer approach for doing this. [The blog entry is here.](http://sciyoshi.com/blog/2008/aug/07/custom-django-manager-excludes-subclasses/)

  • managers
  • models
  • model
  • subclass
  • manager
  • inheritance
  • subclasses
Read More

Manager introspecting attached model

[A comment on a recent blog entry of mine](http://www.b-list.org/weblog/2008/feb/25/managers/#c63422) asked about a setup where one model has foreign keys pointing at it from several others, and how to write a manager which could attach to any of those models and query seamlessly on the relation regardless of what it's named. This is a simple example of how to do it: in this case, both `Movie` and `Restaurant` have foreign keys to `Review`, albeit under different names. However, they both use `ReviewedObjectManager` to provide a method for querying objects whose review assigned a certain rating; this works because an instance of `ReviewedObjectManager` "knows" what model it's attached to, and can introspect that model, using [Django's model-introspection API](http://www.b-list.org/weblog/2007/nov/04/working-models/), to find out the correct name to use for the relation, and then use that to perform the query. Using model introspection in this fashion is something of an advanced topic, but is extremely useful for writing flexible, reusable code. **Also**, note that the introspection cannot be done in the manager's `__init__()` method -- at that point, `self.model` is still `None` (it won't be filled in with the correct model until a bit later) -- so it's necessary to come up with some way to defer the introspection. In this case, I'm doing it in a method that's called when the relation name is first needed, and which caches the result in an attribute.

  • managers
  • models
  • introspection
Read More

Specify a manager for the Admin

This example shows how you can easily limit the objects in the admin by specifying which Manager the admin should use. I haven't seen this documented anywhere (perhaps I've missed it), but it's proven extremely useful to me. The example here will limit objects to those that are attached to the current Site, but you can use any Manager you want (for example, a Manager that shows only published Articles). Finally -- not that I'm suggesting this -- but you *could* combine this with the ThreadLocals trick to show only objects that have been created by that user.

  • managers
  • models
  • admin
  • sites
Read More

Get most-commented objects

This is a pretty straightforward bit of code for getting the most-commented objects of a particular model; just drop it into a custom manager for that model, and you should be good to go. Check the docstring for how to make it look at `Comment` instead of `FreeComment`.

  • managers
  • comments
  • popularity
Read More

more on manager methods

[Snippet #2](http://www.djangosnippets.org/snippets/2/) demonstrated some cool tricks possible with manager methods. This example shows how to assign and use a custom manager method. In this snippet the `belongs_to_user` method returns an Account queryset containing only those accounts associated with the specified user. The method is useful because it hides the implementation of User in the Account model. Line 17 associates the custom manager with the Account model.

  • managers
Read More

Using manager methods

This is part of the user-registration code used on this site (see [the django-registration project on Google Code](http://code.google.com/p/django-registration/) for full source code), and shows a couple of interesting tricks you can do with manager methods. In this case there's a separate `RegistrationProfile` model used to store an activation key and expiration time for a new user's account, and the manager provides a couple of useful methods for working with them: `create_inactive_user` creates a new user and a new `RegistrationProfile` and emails an activation link, `activate_user` knows how to activate a user's account, and `delete_expired_users` knows how to clean out old accounts that were never activated. Putting this code into custom manager methods helps a lot with re-use, because it means that this code doesn't have to be copied over into different views for each site which uses registration, and also makes more sense in terms of design, because these are methods which need to "know about" the model and work with it, and so they belong in a place close to the model.

  • managers
  • registration
Read More

Fetching top items

This is a method from the custom manager for the Snippet model used on this site; the basic idea is to be able to ask for the top `n` "foo", where "foo" is something related to Snippet. For example, you can use `top_items('tag')` to get the top Tags ordered by how many Snippets are associated with them. I have a feeling that I could get this down to one query, but haven't yet put in the time for it.

  • snippets
  • sql
  • managers
  • group-by
Read More

10 snippets posted so far.