[英]Django creating model instances without keyword arguments
In Django, if you want to create a model you can do it as follows: 在Django中,如果要创建模型,可以按以下步骤进行操作:
class SomeModel(models.Model):
a = models.CharField(max_length=10)
b = models.CharField(max_length=20)
c = models.CharField(max_length=30)
d = models.CharField(max_length=40)
e = models.CharField(max_length=50)
f = models.CharField(max_length=60)
Now if you want to create an instance in the shell, you have to do: 现在,如果要在外壳中创建实例,则必须执行以下操作:
> abcdef = SomeModel(a="stuff", b="stuff", c="stuff", d="stuff", e="stuff", f="stuff")
This gets really annoying if you have to keep creating model instances with long property names. 如果必须继续创建具有长属性名的模型实例,这将变得非常烦人。 Is there a way to simply send the arguments like you would with a normal Python object (as in without having to name the variables and just send the variables in order) ?
有没有一种方法可以像发送普通Python对象一样简单地发送自变量(就像不必命名变量并按顺序发送变量一样)?
Like this: 像这样:
> abcdef = SomeModel("stuff", "stuff", "stuff", "stuff", "stuff", "stuff")
As you would with a standard Python class in the init function. 就像在init函数中使用标准Python类一样。
Thanks :) 谢谢 :)
Here is my actual Python model: 这是我实际的Python模型:
class School(models.Model):
urn = models.CharField(max_length=6)
name = models.CharField(max_length=100)
house = models.CharField(max_length=50)
street = models.CharField(max_length=50)
county = models.CharField(max_length=50)
postcode = models.CharField(max_length=8)
def __unicode__(self):
return str(
'URN: ' + self.urn + ', ' +
'Name: ' + self.name + ', ' +
'House: ' + self.house + ', ' +
'Street: ' + self.street + ', ' +
'County: ' + self.county + ', ' +
'Postcode: ' + self.postcode + ', '
)
Have you tried the following code: 您是否尝试过以下代码:
obj = SomeModel(None, "a_stuff", "b_stuff", "c_stuff", "d_stuff", "e_stuff", "f_stuff")
obj.save()
Hope these helps. 希望这些会有所帮助。
you can create instance by doing 你可以通过创建实例
abcdef = SomeModel()
Since instantiating doesnot touch the database, you can assign values later and then do .save()
. 由于实例化不会影响数据库,因此您可以稍后分配值,然后执行
.save()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.