Writing a __init__ function to be used in django model

前端 未结 4 1745
情深已故
情深已故 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:19

    Don't create models with args parameters. If you make a model like so:

     User('name','email')
    

    It becomes very unreadable very quickly as most models require more than that for initialization. You could very easily end up with:

    User('Bert', 'Reynolds', 'me@bertreynolds.com','0123456789','5432106789',....)
    

    Another problem here is that you don't know whether 'Bert' is the first or the last name. The last two numbers could easily be a phone number and a system id. But without it being explicit you will more easily mix them up, or mix up the order if you are using identifiers. What's more is that doing it order-based will put yet another constraint on other developers who use this method and won't remember the arbitrary order of parameters.

    You should prefer something like this instead:

    User(
        first_name='Bert',
        last_name='Reynolds',
        email='me@bertreynolds.com',
        phone='0123456789',
        system_id='5432106789',
    )
    

    If this is for tests or something like that, you can use a factory to quickly create models. The factory boy link may be useful: http://factoryboy.readthedocs.org/en/latest/

提交回复
热议问题