码迷,mamicode.com
首页 > 其他好文 > 详细

Django ORM操作

时间:2016-11-27 14:20:32      阅读:434      评论:0      收藏:0      [点我收藏+]

标签:外键   try   django   ges   environ   命令   对象   email   creat   

 

 

 

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
models

 

创建一条记录

#通过命令行执行
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操作

标签:外键   try   django   ges   environ   命令   对象   email   creat   

原文地址:http://www.cnblogs.com/yexiaochong/p/6106252.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!