
法一:
User.objects.create(username="xiaoming",age="2")不需要save
法二:
user = User(username="xiaoming",age="2")user.save()
法三:
user = User()user.username = "xiaoming"user.age = "2"user.save()
法四:
dic = {'user':'yangmv','pwd':'123456'}models.UserInfo.objects.create(**dic)
Model.objects.update_or_create(defaults,**kwargs)dict_info = {'x': 777, 'y': 777,}Model.objects.update_or_create(id=nid,defaults=dict_info)Model.objects.update_or_create(id=nid,pk=npk,defaults=dict_info)id 是要搜索的值(可以多个)id 默认id字段,如果不是要模型加上primary_key=Truedefaults 是要更新的值,如果不存在就创建
django1.4以后加入了新的特性
django.db.models.query.QuerySet.bulk_create()
#!/usr/bin/env pythonimport osos.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")def main():from blog.models import Blogf = open('oldblog.txt')BlogList = []for line in f:title,content = line.split('****')blog = Blog(title=title,content=content)BlogList.append(blog)f.close()Blog.objects.bulk_create(BlogList)if __name__ == "__main__":main()print('Done!')
author = Author.objects.get()author.delete()
Author.objects.filter(id=1).update()models.UserInfo.objects.filter(user='yangmv').update(pwd='520')dic = {'user':'yangmv','pwd':'123456'}models.UserInfo.objects.filter(user='yangmv').update(**dic) # 没试过估计也可以或者obj = models.UserInfo.objects.get(user='yangmv')obj.pwd = '520'obj.save()