复制派生自抽象模型的类的所有字段(Django) [英] Copy all fields of a class derived from an abstract model (Django)

查看:57
本文介绍了复制派生自抽象模型的类的所有字段(Django)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型,分别是从同一抽象模型派生的相同结构的 A B

I have two models A and B of the same structure derived from the same abstract model:

class CommonInfo(models.Model):
    name = models.CharField(max_length=100)
    # ...  # more fields

    class Meta:
        abstract = True

class A(CommonInfo):
    pass

class B(CommonInfo):
    pass

现在具有对象 A ,我想创建一个具有相同字段值的类 B 的对象。

Now having an object of class A, I want to create an object of class B with the same values of fields.

将一个对象的所有字段复制到另一个对象的Django正确方法是什么?

What is the proper Django way to copy all fields of one object to the other?

我知道的唯一方法是枚举所有字段(顺便说一句) ,怎么做?)并将其存储在另一个对象中。但是,有没有更简单的方法?

The only way I know is to enumerate all fields (by the way, how to do it?) of an object and store them in the other object. But is there an easier way?

推荐答案

您可以使用 model_to_dict(..)并在构造 B 对象时使用此字典,例如:

You could use model_to_dict(..) and use this dictionary in the construction of a B object, like:

from django.forms.models import model_to_dict

my_b = B(**model_to_dict(
    my_a,
    fields=[f.name for f in CommonInfo._meta.fields],
))
#  some processing
my_b.save()

请注意,如果 CommonInfo 包含对象的外键,则将复制这些引用,但不会构造新的引用对象。此外,这对许多字段都不起作用,因此您需要排除这些字段(并在以后添加相关对象)。

Note that if the CommonInfo contains foreign keys to objects, then these references will be copied, but no new referred objects will be constructed. Furthermore this will not work for many-to-many fields, so you need to exclude these (and add the related objects later).

这篇关于复制派生自抽象模型的类的所有字段(Django)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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