Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...