为创建对象,可使用该model class的关键字参数初始化该对象,然后使用save()方法将该对象保存到数据库中
from crud_app.models import Blog
b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
b.save()
修改对象属性
b.name = 'new Beatles Blog'
b.save()
创建一个新的Blog对象
b = Blog(name='Cheddar Talk')
创建一个新的Entry对象
e = Entry()
e.headline = 'entry_1'
cheese_blog = Blog.objects.get(name='Cheddar Talk')
e.blog = cheese_blog
from django.utils import timezone
e.pub_date = timezone.now()
e.mod_date = timezone.now()
e.n_comments = 1
e.n_pingbacks = 1
e.rating = 1
e.save()
更新多对多关系字段,使用add()方法
from crud_app.models import Author
joe = Author.objects.create(name='Joe')
entry.authors.add(joe)
或者
john = Author(name='John')
john.save()
entry.authors.add(john)
为多对多字段一次性关键多个对象
paul = Author.objects.create(name='Paul')
george = Author.objects.create(name='George')
entry.authors.add(paul,george)