views:

215

answers:

1

I would like to access the Foo instance foo within my manager method baz:

foo.bar_set.baz()

baz would normally take an argument of Foo type:

BarManager(models.Manager):
    def baz(self, foo=None):
        if foo is None:
            # assume this call originates from
            # a RelatedManager and set `foo`.
            # Otherwise raise an exception
        # do something cool with foo

This way both the first query above and the following one works identically:

Bar.objects.baz(foo)

Bar would have a ForeignKey to Foo:

class Bar(models.Model):
    foo = models.ForeignKey(Foo)
    objects = BarManager()
+1  A: 

If I'm understanding what you want correctly, you need to do this:

 BarManager(models.Manager):
      use_for_related_fields = True

Edit: apparently I managed to miss the point completely. You can use something like this (maybe a bit too "magic" for my taste, but oh well):

class BarManager(models.Manager):
    use_for_related_fields = True

    def bar(self, foo=None):
        if foo == None:
            qs = Foo.objects.all()
            for field_name, field_val in self.core_filters.items():
                field_name = field_name.split('__')[1]
                qs = qs.filter(**{ field_name: field_val })
            foo = qs.get()
        # do k00l stuff with foo
oggy
No, that's not necessary. baz method is already available on Foo.bar_set
muhuk