Creating many objects using django
I'm using django-polymorphic and have a base class with about 8 derived classes. It works great except when I try to create many objects at once, in this case the performance is very poor. My code looks like this:
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()
I've also tried using Parent.objects.bulk_create
, but this doesn't work well with polymorphic-django, because it just creates the base object and not the child objects. When I try to use bulk_create
of each of the child models, it raises ValueError("Can't bulk create an inherited model")
.
Is there a more efficient way of creating many polymorphic objects?
This was implemented in 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()
the return obj from func is used elsewhere :) enjoy
链接地址: http://www.djcxy.com/p/38666.html上一篇: RuntimeWarning:DateTimeField收到一个天真的日期时间
下一篇: 使用django创建许多对象