django(python)重用对象吗?

时间:2015-06-03 01:50:04

标签: python django

假设我的模型包含字段field1

class MyClass(models.Model):

   field1 = models.CharField(max_length=100)

某处我有像

这样的代码
my_object = MyClass()

my_object.field1 = 'a'
my_object.another_field = 'b' # (it's not defined in the model class)

another_object = MyClass()是否有可能another_field set

1 个答案:

答案 0 :(得分:2)

不,another_field对您指定给它的实例是唯一的。无论Django如何,这都是python特有的。在python控制台中试试这个:

>>> class MyClass():
>>>   field1 = "field 1"
>>> x = MyClass()
>>> x.another_field = "another field!"
>>> x.field1
'field 1'
>>> x.another_field
'another field!'
>>> y = MyClass()
>>> y.field1
'field 1'
>>> y.another_field
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute 'another_field'

如果要动态地向类添加新字段,可以通过将其直接添加到类(而不是实例)来实现,如下所示:

>>> MyClass.newer_field = "this is the newest field" 

现在,您可以看到更新的字段可用,甚至是现有对象:

>>> x.newer_field
'this is the newest field'
>>> y.newer_field
'this is the newest field'
相关问题