Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a __init__ function to be used in django model

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') 

When I write the 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 to the database, but when I do User.objects.all(), it doesn't pull anything up unless I take out my __init__ function. Any ideas?

like image 719
victor Avatar asked May 09 '09 16:05

victor


People also ask

What is __ init __ in Django?

__init__ : "__init__" is a reseved method in python classes. It is known as a constructor in object oriented concepts. This method called when an object is created from the class and it allow the class to initialize the attributes of a class.

What is __ init __? Explain with example?

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

What is the correct syntax for defining an __ Init__?

We can declare a __init__ method inside a class in Python using the following syntax: class class_name(): def __init__(self): # Required initialisation for data members # Class methods … …

What is __ str __ In Django model?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model.


2 Answers

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

p = User(name="Fred", email="[email protected]") 

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", "[email protected]") 
like image 93
Baldu Avatar answered Oct 03 '22 07:10

Baldu


Django expects the signature of a model's constructor to be (self, *args, **kwargs), or some reasonable facsimile. Your changing the signature to something completely incompatible has broken it.

like image 32
Ignacio Vazquez-Abrams Avatar answered Oct 03 '22 05:10

Ignacio Vazquez-Abrams