views:

130

answers:

1

Hello, I want to add a new function to the default User model of Django for retrieveing a related list of Model type.

Such Foo model:

class Foo(models.Model):
    owner = models.ForeignKey(User, related_name="owner")
    likes = models.ForeignKey(User, related_name="likes")

........

    #at some view
    user = request.user
    foos= user.get_related_foo_models()

Hwo can this be achieved ?

+2  A: 

You can add a method to the User

from django.contrib import auth
auth.models.User.add_to_class('get_related_foo_models', get_related_foo_models)

Make sure, you have this code within the models.py or some other file which gets imported in the startup of django.

Lakshman Prasad
that's pretty nice! Why is it that this method is not documented? I usually created something like this: http://dpaste.org/IOoy/ (involves "import new" etc.) Is your approach and my much more complicated one doing essentially the same stuff?
mawimawi