Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django User model, adding function

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() 

How can this be achieved?

like image 359
Hellnar Avatar asked May 30 '10 19:05

Hellnar


People also ask

How do I use built in user model in Django?

Django allows you to override the default user model by providing a value for the AUTH_USER_MODEL setting that references a custom model. Method 2 – AUTH_USER_MODEL : AUTH_USER_MODEL is the recommended approach when referring to a user model in a models.py file.

How do I reference a user model in Django?

Referencing the User model Instead of referring to User directly, you should reference the user model using django. contrib. auth. get_user_model() .


2 Answers

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.

like image 197
lprsd Avatar answered Sep 29 '22 12:09

lprsd


This is an update of @Lakshman Prasad's answer. But a full example:

create a file monkey_patching.py in any of your apps::

#app/monkey_patching.py from django.contrib.auth.models import User   def get_user_name(self):     if self.first_name or self.last_name:         return self.first_name + " " + self.last_name     return self.username  User.add_to_class("get_user_name",get_user_name) 

and import it in app's __init__.py file. ie::

#app/__init__.py import monkey_patching 
like image 41
suhailvs Avatar answered Sep 29 '22 12:09

suhailvs