开发者

saving data in Bulk using Django

I have objects A witch has many to many relation ship to object b. Is it possible to save objects A with it's B collection in a bulk ' I mean not to save B objects one by one then add them to A.

for b in b_objects :
   开发者_如何学JAVA A.b_objs.add(b)

A.save()

Thanks


You could dump your model to json (from http://www.djangosnippets.org/snippets/125/):

import sys, os

sys.path.append('/Path/To/Django/Projects/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

from django.core.serializers import serialize
from myproject.myapp import models

model_names = [] # a list of the names of the models you want to export

for model_name in model_names:
    cls = getattr(models, model_name)
    filename = model_name.lower() + ".json"
    file = open(filename, "w")
    file.write(serialize("json", cls.objects.all()))


I don't think so. The ManyToMany relationship is realized with an intermediate table than contains (id, a_id, b_id) tuples. Therefore A must pre-exist (See 'Sample API Usage') and each B must have an id before the intermediate row can be created. I looked at the source in django.db.models.fields.related and although create_many_related_manager has a method called _add_items(), it seems to assume that all of the B items being added already have id fields, meaning they must have been saved beforehand.

I couldn't find anything that would allow the equivalent of A.add(bunch_of_Bs_that_havent_been_saved_yet). The above mentioned example does show add()ing multiple Bs in one shot, but they have all been saved before the add() happens. Sorry.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜