将QuerySet结果插入Django中的表中

时间:2014-12-28 09:03:49

标签: python mysql django django-queryset django-orm

我有一个查询集,我想将该查询集的结果插入数据库表(比如SelectedFeatures)。

all_features = Feature.objects.filter(product_id = selected_product_id)

除了一个字段外,新表和Feature表的结构几乎相同。我是否应该手动插入查询集的所有字段,例如将记录插入表中,还是有其他方法来满足这一要求?

1 个答案:

答案 0 :(得分:1)

我喜欢@ doniyor的解决方案,但如果您需要更多控制(例如,如果字段名称不完全相同),您可以迭代字段并可能做出一些决定:

for feature in Feature.objects.filter(product_id = selected_product_id).all():
    selected_feature = SelectedFeature()
    for attr in SelectedFeature._meta.get_all_field_names():
         selected_feature.setattr(attr, feature.getattr(attr))
    selected_feature.save()