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()
    
  • 相关阅读:
    python面向对象(一)
    ls和cd命令详解
    SHELL 中的变量
    Shell基础
    Python版飞机大战
    Python模块制作
    Linux的cut命令
    Linux中的wc命令
    Ubuntu系统下adb devices 不能显示手机设备
    app耗电量测试工具--PowerTutor
  • 原文地址:https://www.cnblogs.com/zhangqigao/p/5795870.html
Copyright © 2011-2022 走看看