首页 > 代码库 > Django ORM操作
Django ORM操作
ORM 常用操作进阶操作
#!/usr/bin/env python #_*_ coding:utf8 _*_ from __future__ import unicode_literals from django.db import models class Blog(models.Model): name = models.CharField(max_length=128) content = models.TextField() def __unicode__(self): return self.name class Author(models.Model): name = models.CharField(max_length=64) email = models.EmailField() def __unicode__(self): return self.name class Entry(models.Model): blog = models.ForeignKey(Blog) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author) n_comments = models.IntegerField() n_pingbacks = models.IntegerField() rating = models.IntegerField() def __unicode__(self): return self.headline
创建一条记录
#通过命令行执行 C:\Users\Administrator\PycharmProjects\Study>python manage.py shell >>> from blog.models import Blog >>> b = Blog(name="Beatles Blog",content=‘ALL the lastest Beatles news‘) >>> b.save()
在自己的脚本里调用django models
#!/usr/bin/env python #_*_ coding:utf8 _*_ import os os.environ[‘DJANGO_SETTINGS_MODULE‘] = ‘Study.settings‘ import django django.setup() from blog import models entry = models.Entry.objects.get(pk=1) print (entry)
处理带外键关联或多关联的对象
ForeignKey的关联
from blog import models entry = models.Entry.objects.get(pk=1) cheese_blog = models.Blog.objects.get(name=‘科技‘) entry.blog = cheese_blog entry.save()
ManyToManyField关联
>>> from blog.models import Author >>> joe = Author.objects.create(name="Joe") >>> entry.authors.add(joe) 添加多个ManyToMany对象 >>> 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)
Django ORM操作
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。