tags:

views:

28

answers:

1

Say I have a model with a foreign key to a Django Auth user:

class Something(models.Model):

    user = models.ForeignKey(User, related_name='something')

I can then access this model through a RelatedManager:

u = User.objects.create_user('richardhenry', '[email protected]', 'password')
u.something.all()

My question is, if I create a SomethingManager and define some methods on it:

class SomethingManager(models.Manager):

    def do_something(self):
        pass

Is it possible to get the original User object (as in, the variable u) within the do_something() method? (Through the related manager; passing it in via the method args isn't what I'm after.)

+2  A: 

Managers are only directly connected to the model they manage. So in this case, your Manager would be connected to Something, but not directly to User.

Also, Managers begin with querysets, not objects, so you'll have to work from there.

Keep in mind that to use your custom methods with a RelatedManager you need to set use_for_related_fields = True in your Manager.

So to get to the user, you'd have to be a bit roundabout and get the object, then the user:

def do_something(
    ids = self.get_query_set().values_list('user__id', flat=True)
    return User.objects.filter(id__in=ids).distinct()

The above should return just one user, you could add a .get() at the end to get the object instead of a queryset, but I like returning querysets since you can keep chaining them.

Gabriel Hurley