Django从多个模型创建模型的简便方法

时间:2015-02-18 21:08:21

标签: django python-2.7

鉴于这些伪模型:

class A(models.Model):
    aa = models.CharField()
    ab = models.CharField()
    # ... many other fields

class B(models.Model):
    ba = models.CharField()
    bb = models.CharField()
    # ... many other fields

class C(models.Model):
    ca = models.CharField()
    cb = models.CharField()
    # ... many other fields

现在我有另一个聚合 SOME 上述模型属性的模型,就像这样,将其视为存储快照的审计表:

class Agg(models.Model):
    aa = models.CharField() # from A
    bb = models.CharField() # from B
    ca = models.CharField() # from C
    # ... many other fields from A, B and C

创建Agg时,我需要明确地命名所有属性,如下所示:

Agg.objects.create(
         aa=a_instance.aa, 
         bb=b_instance.bb, 
         ca=c_instance.ca, # and so on ...
)

如果模型有很多字段,这很麻烦。有没有更好/更短的方法呢?

1 个答案:

答案 0 :(得分:2)

您可以使用Meta.get_all_field_names()方法获取Avg字段列表,然后从ABC复制具有相同名称的字段实例:

def create_avg(*args):
    data = {}
    for field_name in Avg._meta.get_all_field_names():
        if field_name != 'id':
            for instance in args:
                if hasattr(instance, field_name):
                    data[field_name] = getattr(instance, field_name)
                    break
    Avg.objects.create(**data)

然后将此函数称为:

avg_instance = create_avg(a_instance, b_instance, c_instance)

此解决方案无法处理ManyToMany字段,但可以轻松修改以进行此操作。