django ORM

http://www.cnblogs.com/alex3714/articles/5512568.html

常用ORM操作

一、示例Models

from django.db import models

class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField() def __str__(self): # __unicode__ on Python 2
return self.name class Author(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField() def __str__(self): # __unicode__ on Python 2
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 __str__(self): # __unicode__ on Python 2
return self.headline

二、创建数据

from blog.models import blog
#把数据插入到表中然后提交
b = blog(name='zhangsan',tagline='All the latest Beatles news.')
b.save()

This performs an INSERT SQL statement behind the scenes. Django doesn’t hit the database until you explicitly call save().

The save() method has no return value.

注意:此次执行相当于sql语句中的INSERT 语句,Django 不直接操作数据库直到调用save()方法,save()没有任何返回值

三、处理外键或多对多关系的对象

①外键(ForeignKey)的关联

from blog.models import Entry,Blog

entry = Entry.objects.get(pk=1)
cheese_blog = Blog.objects.get(name="Cheddar Talk")
entry.blog = cheese_blog
entry.save()
上一篇:curl 详解【转】


下一篇:php curl详解用法[真的详解]