Writing the __init__ function to be used in the django model

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

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

When I write a model, I have:

 def __init__(self, name, email, house_id, password): models.Model.__init__(self) self.name = name self.email = email 

This works, and I can save the object in the database, but when I execute User.objects.all() , it does not pull anything out unless I User.objects.all() its __init__ function. Any ideas?

+62
python django django-models
May 09 '09 at 16:23
source share
4 answers

Relying on Django's built-in functionality and passing named parameters is the easiest way.

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

But if you are set to save a few keystrokes, I would 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") 
+96
May 09 '09 at 17:55
source share

Django expects the signature of the model constructor to be (self, *args, **kwargs) or some reasonable facsimile. Your change of signature to something completely incompatible violated it.

+41
May 09 '09 at 17:10
source share

The correct answer is to avoid overriding __init__ and write a class as described in the Django docs .

But you can do it the way you try, you just need to add *args, **kwargs to accept your __init__ , and pass them to the super method call.

 def __init__(self, name, email, house_id, password, *args, **kwargs): super(models.Model, self).__init__(self, *args, **kwargs) self.name = name self.email = email 
+13
Jan 29 '15 at 15:45
source share

Do not create models with args parameters. If you make a model like this:

  User('name','email') 

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

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

Another problem is that you don’t know if Bert is the first or the last. The last two numbers may simply be a phone number and a system identifier. But without its explicit you will be easier to mix them or mix order, if you use identifiers. Moreover, doing this on the basis of an order will be another limitation for other developers who use this method and will not remember the arbitrary order of the parameters.

Instead, you should prefer something like this:

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

If it's for tests or something like that, you can use factory to quickly create models. Link to factory link may be useful: http://factoryboy.readthedocs.org/en/latest/

+2
Jan 20 '15 at 16:13
source share



All Articles