我正在使用django-polymorphic并且拥有一个包含大约8个派生类的基类。除非我尝试一次创建多个对象,否则它的效果很好,在这种情况下性能非常差。我的代码如下所示:
class Parent(PolymorphicModel):
...
class DerivedA(Parent):
...
class DerivedB(Parent):
...
@transaction.commit_on_success
def create_objects()
for model_class in (DerivedA, DerivedB...):
instance = model_class(...)
instance.save()
我也尝试使用Parent.objects.bulk_create
,但这对于polymorphic-django不起作用,因为它只是创建基础对象而不是子对象。当我尝试使用每个子模型的bulk_create
时,它会引发ValueError("Can't bulk create an inherited model")
。
是否有更有效的方法来创建许多多态对象?
答案 0 :(得分:0)
这是在django admin
中实现的models.py
class BuildScript(models.Model):
fields ...bla bla
class POLY_BuildScript(BuildScript):
class Meta:
verbose_name = "POLY"
fields...bla bla
admin.py
#just after the imports (func stands alone)
def save_with_parent_fields(obj):
obj.build = obj.pbuild
obj.branch = obj.pbranch
return obj
class BuildScriptAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.executer = request.user.userprofile
obj.save()
class POLY_BuildScriptAdmin(BuildScriptAdmin):
def save_model(self, request, obj, form, change):
save_with_parent_fields(obj)
obj.executer = request.user.userprofile
obj.save()
来自func的返回obj在别处使用:) 享受