将一个python / django对象从父模型移动到一个子类(子类) [英] Move a python / django object from a parent model to a child (subclass)
问题描述
例如,我有一个Swallow模型。现在,我正在做欧洲(燕子)和非洲人(燕子)。我想采取一些但不是全部的燕子对象使他们是欧洲人或非洲人,取决于他们是否迁徙。
我如何移动他们?
很久以后,但我需要做类似的事情,找不到什么。我发现答案埋在一些源代码 here 中,但也写了一个足够的示例类方法。
class AfricanSwallow(Swallow):
@classmethod
def save_child_from_parent(cls,swallow,new_attrs):
输入:
- 燕子:我们要创建的燕子的实例为AfricanSwallow
- new_attrs:AfricanSwallow的新属性字典
改编自:
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
在swallow._meta.fields中的字段:
new_attrs [field.name] = getattr(swallow,field.name)
s = AfricanSwallow(** new_attrs)
s.save ()
return s
我无法弄清楚如何让我的表单验证但是使用这种方法;所以肯定可以提高一点;可能意味着数据库重构可能是最好的长期解决方案...
I am subclassing an existing model. I want many of the members of the parent class to now, instead, be members of the child class.
For example, I have a model Swallow. Now, I am making EuropeanSwallow(Swallow) and AfricanSwallow(Swallow). I want to take some but not all Swallow objects make them either EuropeanSwallow or AfricanSwallow, depending on whether they are migratory.
How can I move them?
I know this is much later, but I needed to do something similar and couldn't find much. I found the answer buried in some source code here, but also wrote an example class-method that would suffice.
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
I couldn't figure out how to get my form validation to work with this method however; so it certainly could be improved more; probably means a database refactoring might be the best long-term solution...
这篇关于将一个python / django对象从父模型移动到一个子类(子类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!