Best way to add convenience methods to a Django Auth User model?

前端 未结 5 1676
春和景丽
春和景丽 2020-12-13 19:34

I want to add a convenience/model method to the django.contrib.auth.models.User model. What is the best practice for doing this since, last time I checked, ext

5条回答
  •  一向
    一向 (楼主)
    2020-12-13 20:35

    if you want to add custom methods to the User model, I would recommend monkey_patching:

    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
    

提交回复
热议问题