Friday, May 6, 2011

Writing a __init__ function to be used in django model

Hi,

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?

From stackoverflow
  • 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.

  • 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
    def create(name, email)
      return User(name=name, email=email)
    create = staticmethod(create)
    
    # Use it
    p = User.create("Fred", "fred@example.com")
    
    Carl Meyer : Yeah, a factory method is the way to go here. You could also consider putting it on the Manager. Messing with the constructor signature will definitely break things.
    PirosB3 : Thanks man!! helped me a lot
    Wahnfrieden : @classmethod on create is also nicer

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.