Django User model, adding function

后端 未结 3 1724
醉话见心
醉话见心 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:23

    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
    

提交回复
热议问题