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?
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.
Referencing the User model Instead of referring to User directly, you should reference the user model using django. contrib. auth. get_user_model() .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With