views:

148

answers:

2
class SupercalifragilisticexpialidociousManager(models.Manager):
    # Sorry, I'm sick of Foo and Spam for now.
    def get_query_set(self, account=None):
        return super(SupercalifragilisticexpialidociousManager,
                     self).get_query_set().filter(uncle=model_thats_using_this_manager_instance.uncle)

The magic I'm looking for is the "uncle=model_thats_using_this_manager_instance.uncle". It seems like I should be able to do this somehow. I know I could say self.model to get the model, but how to get the instance?

+2  A: 

It doesn't make sense to ask for an instance when you're using a manager. Managers are class-level attributes - if you try and do foo.objects.all() where foo is an instance of Supercalifragilisticexpialidocious, you will explicitly get an error:

AttributeError: Manager isn't accessible via Supercalifragilisticexpialidocious instances
Daniel Roseman
Thanks Daniel. You're example helped me to understand the context in which managers exist. I still need to find a way to better handle this situation application-wide vs having to write special code hither and thither.
orokusaki
+2  A: 

AFAK you cannot access the model from inside a manager. It doesn't make sense as managers operate on the whole table.

You should do something like this in the model:

class Model(models.Model):
    # some attributes here
    def getAllRelativesWithSameUncle(self):
        return self.objects.filter(uncle = self.uncle)

or in the manager:

class SupercalifragilisticexpialidociousManager(models.Manager):
    def getSameRelativesFor(self, model_instance):
        return self.get_query_set().filter(uncle=model_instance.uncle)
Felix Kling
model method makes much more sense
Dmitry Shevchenko
I think you meant to say uncle=model_instance and (self, model_instance) rather than using the model itself as the filtering attribute.
orokusaki
Of course, thats why it is written in small letters ;) (I confess it could be misunderstood). Changed it....
Felix Kling