Tuesday, January 25, 2011

Re: Getting hold of an instance of a model from inside RelatedManager

On Tuesday, January 25, 2011 3:34:03 PM UTC, kmpm wrote:
I have some issues with getting hold of the instance of a Model to which a RelatedManager got contributed to.
Is that at all possible and if so, how?

From my_method below I can get hold of the model RelatedStuff by calling self.model but that really doesn't get me there.

class MainStuff(models.Model):
    ....
    
class RelatedStuff(models.Model):
    ...
    main = models.ForeignKey(MainStuff)
    objects = CustomManager()

class CustomManager(models.Manager):
    use_for_related_fields=True
    
    def my_method(self):
        #here I would like to access the instance of MainStuff to which this got contributed



Interesting question. Unfortunately, looking at the code, it doesn't seem like you can. Django creates a new RelatedManager class every time, but it does this via a closure - and the instance is only accessible within the closure.

There are probably good reasons why it's done that way (I suspect passing the instance as a parameter and making it available as an attribute would cause a persistent reference to be kept, which would mean that the instance would never be garbage-collected).
--
DR.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment