首页 > 代码库 > 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
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操作