Django User model, adding function

房东的猫 提交于 2019-12-03 05:38:37

问题


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?


回答1:


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.




回答2:


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



回答3:


It's not unusual to substitute user model as it is stated in the docs: https://docs.djangoproject.com/es/1.9/topics/auth/customizing/#substituting-a-custom-user-model, so, having this into account, it is better to get the user model class with the following code:

from django.contrib.auth import get_user_model
UserModel = get_user_model()

Afterwards, you can use this UserModel to add functionality as @Lakshman Prasad suggests: UserModel.add_to_class('get_related_foo_models', get_related_foo_models).


In order to get the code executed only once I prefer to use Django application config classes (https://docs.djangoproject.com/es/1.9/ref/applications/), so a full working example will be:

# myapp/__init__.py
default_app_config = 'myapp.apps.MyAppConfig'

# myapp/apps.py
from django.apps import AppConfig
from django.contrib.auth import get_user_model


class MyAppConfig(AppConfig):
    name = 'myapp'
    verbose_name = 'MyApp'

    def ready(self):
        # Add some functions to user model:
        def custom_function(self):
            # Do whatsoever
            pass

        UserModel = get_user_model()
        UserModel.add_to_class('custom_function', custom_function)


来源:https://stackoverflow.com/questions/2939941/django-user-model-adding-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!