编写一个__init__函数以在django模型中使用 [英] Writing a __init__ function to be used in django model

查看:817
本文介绍了编写一个__init__函数以在django模型中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的一个模型编写一个 __ init __ 函数,以便我可以通过执行

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

当我编写模型时,我有

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

这个工作,我可以将对象保存到数据库,但是当我做User.objects.all()时,它不会拉任何东西,除非我拿出我的 __ init __ 函数。任何想法?

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?

推荐答案

依靠Django的内置功能和传递命名参数将是最简单的方法。 >

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
@classmethod
def create(cls, name, email):
  return cls(name=name, email=email)

# Use it
p = User.create("Fred", "fred@example.com")

这篇关于编写一个__init__函数以在django模型中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆