将一个python / django对象从父模型移动到一个子类(子类) [英] Move a python / django object from a parent model to a child (subclass)

查看:100
本文介绍了将一个python / django对象从父模型移动到一个子类(子类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对现有的模型进行子类化。现在,我想要父类的许多成员,而是成为子类的成员。



例如,我有一个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屋!

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