zoukankan      html  css  js  c++  java
  • 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()
    
  • 相关阅读:
    线程安全的简单理解
    单链表 之 判断两链表是否交叉
    React组件间的通信
    input type=file美化
    Array.prototype.slice.call(arguments)
    ES5 数组方法every和some
    nodejs学习之表单提交(1)
    ES5 数组方法reduce
    ES5 数组方法map
    ES5 数组方法forEach
  • 原文地址:https://www.cnblogs.com/zhangqigao/p/5795870.html
Copyright © 2011-2022 走看看