鍍金池/ 教程/ Python/ Models
更上一層樓
歸檔, AboutMe和標簽分類
動態(tài)URL
Django簡介
Models
項目與APP
Template
開發(fā)環(huán)境和Django安裝
多說,markdown和代碼高亮
Admin
Views和URL
搜索和ReadMore
RSS和分頁

Models

Django Model

  • 每一個Django Model都繼承自django.db.models.Model
  • Model當中每一個屬性attribute都代表一個database field
  • 通過Django Model API可以執(zhí)行數(shù)據(jù)庫的增刪改查, 而不需要寫一些數(shù)據(jù)庫的查詢語句

設(shè)置數(shù)據(jù)庫

Django項目建成后, 默認設(shè)置了使用SQLite數(shù)據(jù)庫, 在my_blog/my_blog/setting.py中可以查看和修改數(shù)據(jù)庫設(shè)置:

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }

還可以設(shè)置其他數(shù)據(jù)庫, 如MySQL, PostgreSQL, 現(xiàn)在為了簡單, 使用默認數(shù)據(jù)庫設(shè)置

創(chuàng)建models

在my_blog/article/models.py下編寫如下程序:

    from django.db import models

    # Create your models here.
    class Article(models.Model) :
        title = models.CharField(max_length = 100)  #博客題目
        category = models.CharField(max_length = 50, blank = True)  #博客標簽
        date_time = models.DateTimeField(auto_now_add = True)  #博客日期
        content = models.TextField(blank = True, null = True)  #博客文章正文

        def __unicode__(self) :
            return self.title

        class Meta:  #按時間下降排序
            ordering = ['-date_time']

其中__unicode__(self) 函數(shù)Article對象要怎么表示自己, 一般系統(tǒng)默認使用`` 來表示對象, 通過這個函數(shù)可以告訴系統(tǒng)使用title字段來表示這個對象

  • CharField 用于存儲字符串, max_length設(shè)置最大長度
  • TextField 用于存儲大量文本
  • DateTimeField 用于存儲時間, auto_now_add設(shè)置True表示自動設(shè)置對象增加時間

同步數(shù)據(jù)庫

    $ python manage.py migrate #命令行運行該命令

因為我們已經(jīng)執(zhí)行過該命令會出現(xiàn)如下提示

    Operations to perform:
      Apply all migrations: admin, contenttypes, sessions, auth
    Running migrations:
      No migrations to apply.
      Your models have changes that are not yet reflected in a migration, and so won't be applied.
      Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.

那么現(xiàn)在需要執(zhí)行下面的命令

    $ python manage.py makemigrations
    #得到如下提示
    Migrations for 'article':
      0001_initial.py:
        - Create model Article

現(xiàn)在重新運行以下命令

    $ python manage.py migrate
    #出現(xiàn)如下提示表示操作成功
    Operations to perform:
      Apply all migrations: auth, sessions, admin, article, contenttypes
    Running migrations:
      Applying article.0001_initial... OK

migrate命令按照app順序建立或者更新數(shù)據(jù)庫, 將models.py與數(shù)據(jù)庫同步

現(xiàn)在我們進入Django中的交互式shell來進行數(shù)據(jù)庫的增刪改查等操作

    $ python manage.py shell
    Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  5 2014, 20:42:22)
    [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>>

這里進入Django的shell和python內(nèi)置的shell是非常類似的

    >>> from article.models import Article
    >>> #create數(shù)據(jù)庫增加操作
    >>> Article.objects.create(title = 'Hello World', category = 'Python', content = '我們來做一個簡單的數(shù)據(jù)庫增加操作')

    >>> Article.objects.create(title = 'Django Blog學習', category = 'Python', content = 'Django簡單博客教程')

    >>> #all和get的數(shù)據(jù)庫查看操作
    >>> Article.objects.all()  #查看全部對象, 返回一個列表, 無對象返回空list
    [, ]
    >>> Article.objects.get(id = 1)  #返回符合條件的對象

    >>> #update數(shù)據(jù)庫修改操作
    >>> first = Article.objects.get(id = 1)  #獲取id = 1的對象
    >>> first.title
    'Hello World'
    >>> first.date_time
    datetime.datetime(2014, 12, 26, 13, 56, 48, 727425, tzinfo=)
    >>> first.content
    '我們來做一個簡單的數(shù)據(jù)庫增加操作'
    >>> first.category
    'Python'
    >>> first.content = 'Hello World, How are you'
    >>> first.content  #再次查看是否修改成功, 修改操作就是點語法
    'Hello World, How are you'

    >>> #delete數(shù)據(jù)庫刪除操作
    >>> first.delete()
    >>> Article.objects.all()  #此時可以看到只有一個對象了, 另一個對象已經(jīng)被成功刪除
    []

    Blog.objects.all()  # 選擇全部對象
    Blog.objects.filter(caption='blogname')  # 使用 filter() 按博客題目過濾
    Blog.objects.filter(caption='blogname', id="1") # 也可以多個條件
    #上面是精確匹配 也可以包含性查詢
    Blog.objects.filter(caption__contains='blogname')

    Blog.objects.get(caption='blogname') # 獲取單個對象 如果查詢沒有返回結(jié)果也會拋出異常

    #數(shù)據(jù)排序
    Blog.objects.order_by("caption")
    Blog.objects.order_by("-caption")  # 倒序

    #如果需要以多個字段為標準進行排序(第二個字段會在第一個字段的值相同的情況下被使用到),使用多個參數(shù)就可以了
    Blog.objects.order_by("caption", "id")

    #連鎖查詢
    Blog.objects.filter(caption__contains='blogname').order_by("-id")

    #限制返回的數(shù)據(jù)
    Blog.objects.filter(caption__contains='blogname')[0]
    Blog.objects.filter(caption__contains='blogname')[0:3]  # 可以進行類似于列表的操作

當然還有更多的API, 可以查看官方文檔

上一篇:Django簡介下一篇:項目與APP