django多保存数据
SavingForeignKeyandManyToManyFieldfields
Updating aForeignKeyfield works exactly the same way as saving a normal field -- simply assign an object of the right type to the field in question. This example updates theblogattribute of anEntryinstanceentry:
>>> from blog.models import Entry
>>> entry = Entry.objects.get(pk=1)
>>> cheese_blog = Blog.objects.get(name="Cheddar Talk")
>>> entry.blog = cheese_blog
>>> entry.save()
Updating aManyToManyFieldworks a little differently -- use theadd()method on the field to add a record to the relation. This example adds theAuthorinstancejoeto theentryobject:
>>> from blog.models import Author
>>> joe = Author.objects.create(name="Joe")
>>> entry.authors.add(joe)
To add multiple records to aManyToManyFieldin one go, include multiple arguments in the call toadd(), like this:
>>> john = Author.objects.create(name="John")
>>> paul = Author.objects.create(name="Paul")
>>> george = Author.objects.create(name="George")
>>> ringo = Author.objects.create(name="Ringo")
>>> entry.authors.add(john, paul, george, ringo)