Writing a __init__ function to be used in django model

前端 未结 4 1731
情深已故
情深已故 2020-11-29 04:49

I\'m trying to write an __init__ function for one of my models so that I can create an object by doing:

p = User(\'name\',\'email\')
         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 05:42

    Relying on Django's built-in functionality and passing named parameters would be the simplest way to go.

    p = User(name="Fred", email="fred@example.com")
    

    But if you're set on saving some keystrokes, I'd suggest adding a static convenience method to the class instead of messing with the initializer.

    # In User class declaration
    @classmethod
    def create(cls, name, email):
      return cls(name=name, email=email)
    
    # Use it
    p = User.create("Fred", "fred@example.com")
    

提交回复
热议问题