jMy*_*les 6 django django-models django-orm
我是现有模型的子类.我现在想要父类的许多成员,而不是子类的成员.
例如,我有一个模型Swallow.现在,我正在制作EuropeanSwallow(Swallow)和AfricanSwallow(Swallow).我想采取一些但不是所有Swallow对象使它们成为EuropeanSwallow或AfricanSwallow,这取决于它们是否是迁徙的.
我该怎么移动它们?
这有点像黑客,但这有效:
swallow = Swallow.objects.get(id=1)
swallow.__class__ = AfricanSwallow
# set any required AfricanSwallow fields here
swallow.save()
Run Code Online (Sandbox Code Playgroud)
我知道这要晚得多,但我需要做类似的事情并且找不到多少.我在这里找到了一些源代码中的答案,但也写了一个足够的示例类方法.
class AfricanSwallow(Swallow):
@classmethod
def save_child_from_parent(cls, swallow, new_attrs):
"""
Inputs:
- swallow: instance of Swallow we want to create into AfricanSwallow
- new_attrs: dictionary of new attributes for AfricanSwallow
Adapted from:
https://github.com/lsaffre/lino/blob/master/lino/utils/mti.py
"""
parent_link_field = AfricanSwallow._meta.parents.get(swallow.__class__, None)
new_attrs[parent_link_field.name] = swallow
for field in swallow._meta.fields:
new_attrs[field.name] = getattr(swallow, field.name)
s = AfricanSwallow(**new_attrs)
s.save()
return s
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何使用此方法进行表单验证; 所以它当然可以得到更多改善; 可能意味着数据库重构可能是最好的长期解决方案......
| 归档时间: |
|
| 查看次数: |
2495 次 |
| 最近记录: |