Django User model, adding function

后端 未结 3 1729
醉话见心
醉话见心 2021-02-01 03:56

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


        
3条回答
  •  悲哀的现实
    2021-02-01 04:28

    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)
    

提交回复
热议问题