亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Django多數(shù)據(jù)庫的實現(xiàn)過程詳解

 更新時間:2019年08月01日 09:47:02   作者:再見紫羅蘭  
這篇文章主要介紹了Django多數(shù)據(jù)庫的實現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

有些項目可能涉及到使用多個數(shù)據(jù)庫的情況,方法很簡單。

1.在settings中設(shè)定DATABASE

比如要使用兩個數(shù)據(jù)庫:

DATABASES = {
  'default': {
    'NAME': 'app_data',
    'ENGINE': 'django.db.backends.postgresql',
    'USER': 'postgres_user',
    'PASSWORD': 's3krit'
  },
  'users': {
    'NAME': 'user_data',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_user',
    'PASSWORD': 'priv4te'
  }
}

這樣就確定了2個數(shù)據(jù)庫,別名一個為default,一個為user。數(shù)據(jù)庫的別名可以任意確定。

default的別名比較特殊,一個Model在路由中沒有特別選擇時,默認使用default數(shù)據(jù)庫。

當(dāng)然,default也可以設(shè)置為空:

DATABASES = {
  'default': {},
  'users': {
    'NAME': 'user_data',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_user',
    'PASSWORD': 'superS3cret'
  },
  'customers': {
    'NAME': 'customer_data',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_cust',
    'PASSWORD': 'veryPriv@ate'
  }
}

這樣,因為沒有了默認的數(shù)據(jù)庫,就需要為所有的Model,包括使用的第三方庫中的Model做好數(shù)據(jù)庫路由選擇。

2.為需要做出數(shù)據(jù)庫選擇的Model規(guī)定app_label

class MyUser(models.Model):
  ...
   class Meta:
    app_label = 'users'

3.寫Database Routers

Database Router用來確定一個Model使用哪一個數(shù)據(jù)庫,主要定義以下四個方法:

db_for_read(model, **hints)

規(guī)定model使用哪一個數(shù)據(jù)庫讀取。

db_for_write(model, **hints)

規(guī)定model使用哪一個數(shù)據(jù)庫寫入。

allow_relation(obj1, obj2, **hints)

確定obj1和obj2之間是否可以產(chǎn)生關(guān)聯(lián), 主要用于foreign key和 many to many操作。

allow_migrate(db, app_label, model_name=None, **hints)

確定migrate操作是否可以在別名為db的數(shù)據(jù)庫上運行。

一個完整的例子:

數(shù)據(jù)庫設(shè)定:

DATABASES = {
  'default': {},
  'auth_db': {
    'NAME': 'auth_db',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_user',
    'PASSWORD': 'swordfish',
  },
  'primary': {
    'NAME': 'primary',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_user',
    'PASSWORD': 'spam',
  },
  'replica1': {
    'NAME': 'replica1',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_user',
    'PASSWORD': 'eggs',
  },
  'replica2': {
    'NAME': 'replica2',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_user',
    'PASSWORD': 'bacon',
  },
}

如果想要達到如下效果:

app_label為auth的Model讀寫都在auth_db中完成,其余的Model寫入在primary中完成,讀取隨機在replica1和replica2中完成。

auth:

class AuthRouter(object):
  """
  A router to control all database operations on models in the
  auth application.
  """
  def db_for_read(self, model, **hints):
    """
    Attempts to read auth models go to auth_db.
    """
    if model._meta.app_label == 'auth':
      return 'auth_db'
    return None
 
  def db_for_write(self, model, **hints):
    """
    Attempts to write auth models go to auth_db.
    """
    if model._meta.app_label == 'auth':
      return 'auth_db'
    return None
 
  def allow_relation(self, obj1, obj2, **hints):
    """
    Allow relations if a model in the auth app is involved.
    """
    if obj1._meta.app_label == 'auth' or \
      obj2._meta.app_label == 'auth':
      return True
    return None
 
  def allow_migrate(self, db, app_label, model_name=None, **hints):
    """
    Make sure the auth app only appears in the 'auth_db'
    database.
    """
    if app_label == 'auth':
      return db == 'auth_db'
    return None

這樣app_label為auth的Model讀寫都在auth_db中完成,允許有關(guān)聯(lián),migrate只在auth_db數(shù)據(jù)庫中可以運行。

其余的:

import random
 
class PrimaryReplicaRouter(object):
  def db_for_read(self, model, **hints):
    """
    Reads go to a randomly-chosen replica.
    """
    return random.choice(['replica1', 'replica2'])
 
  def db_for_write(self, model, **hints):
    """
    Writes always go to primary.
    """
    return 'primary'
 
  def allow_relation(self, obj1, obj2, **hints):
    """
    Relations between objects are allowed if both objects are
    in the primary/replica pool.
    """
    db_list = ('primary', 'replica1', 'replica2')
    if obj1._state.db in db_list and obj2._state.db in db_list:
      return True
    return None
 
  def allow_migrate(self, db, app_label, model_name=None, **hints):
    """
    All non-auth models end up in this pool.
    """
    return True

這樣讀取在隨機在replica1和replica2中完成,寫入使用primary。

最后在settings中設(shè)定:

DATABASE_ROUTERS = ['path.to.AuthRouter', 'path.to.PrimaryReplicaRouter']

就可以了。

進行migrate操作時:

$ ./manage.py migrate
$ ./manage.py migrate --database=users

migrate操作默認對default數(shù)據(jù)庫進行操作,要對其它數(shù)據(jù)庫進行操作,可以使用--database選項,后面為數(shù)據(jù)庫的別名。

與此相應(yīng)的,dbshell,dumpdata,loaddata命令都有--database選項。

也可以手動的選擇路由:

查詢:

>>> # This will run on the 'default' database.
>>> Author.objects.all()
 
>>> # So will this.
>>> Author.objects.using('default').all()
 
>>> # This will run on the 'other' database.
>>> Author.objects.using('other').all()

保存:

>>> my_object.save(using='legacy_users')

移動:

>>> p = Person(name='Fred')
>>> p.save(using='first') # (statement 1)
>>> p.save(using='second') # (statement 2)

以上的代碼會產(chǎn)生問題,當(dāng)p在first數(shù)據(jù)庫中第一次保存時,會默認生成一個主鍵,這樣使用second數(shù)據(jù)庫保存時,p已經(jīng)有了主鍵,這個主鍵如果未被使用不會產(chǎn)生問題,但如果先前被使用了,就會覆蓋原先的數(shù)據(jù)。

有兩個解決方法;

1.保存前清除主鍵:

>>> p = Person(name='Fred')
>>> p.save(using='first')
>>> p.pk = None # Clear the primary key.
>>> p.save(using='second') # Write a completely new object.

2.使用force_insert

>>> p = Person(name='Fred')
>>> p.save(using='first')
>>> p.save(using='second', force_insert=True)

刪除:

從哪個數(shù)據(jù)庫取得的對象,從哪刪除

>>> u = User.objects.using('legacy_users').get(username='fred')
>>> u.delete() # will delete from the `legacy_users` database

如果想把一個對象從legacy_users數(shù)據(jù)庫轉(zhuǎn)移到new_users數(shù)據(jù)庫:

>>> user_obj.save(using='new_users')
>>> user_obj.delete(using='legacy_users')

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python協(xié)程原理全面分析

    Python協(xié)程原理全面分析

    協(xié)程(co-routine,又稱微線程、纖程)是一種多方協(xié)同的工作方式。協(xié)程不是進程或線程,其執(zhí)行過程類似于Python函數(shù)調(diào)用,Python的asyncio模塊實現(xiàn)的異步IO編程框架中,協(xié)程是對使用async關(guān)鍵字定義的異步函數(shù)的調(diào)用
    2023-02-02
  • python?特有語法推導(dǎo)式的基本使用

    python?特有語法推導(dǎo)式的基本使用

    python中有一種特有的語法,就是推導(dǎo)式(又稱為解析式)。推導(dǎo)式是可以從一個數(shù)據(jù)序列構(gòu)建另一個新的數(shù)據(jù)序列的結(jié)構(gòu)體
    2022-03-03
  • 深入解析Python中的lambda表達式的用法

    深入解析Python中的lambda表達式的用法

    這篇文章主要介紹了深入解析Python中的lambda表達式的用法,包括其與def之間的區(qū)別,需要的朋友可以參考下
    2015-08-08
  • Python并發(fā)concurrent.futures和asyncio實例

    Python并發(fā)concurrent.futures和asyncio實例

    這篇文章主要介紹了Python并發(fā)concurrent.futures和asyncio實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • Python約瑟夫生者死者小游戲?qū)嵗v解

    Python約瑟夫生者死者小游戲?qū)嵗v解

    在本篇文章里小編給大家分享的是一篇關(guān)于Python約瑟夫生者死者小游戲?qū)嵗v解內(nèi)容,有興趣的朋友們可以測試學(xué)習(xí)下。
    2021-01-01
  • Python實現(xiàn)將文本生成二維碼的方法示例

    Python實現(xiàn)將文本生成二維碼的方法示例

    這篇文章主要介紹了Python實現(xiàn)將文本生成二維碼的方法,結(jié)合完整實例形式分析了Python生成二維碼操作的具體步驟與相關(guān)實現(xiàn)技巧,需要的朋友可以參考下
    2017-07-07
  • TensorFlow中權(quán)重的隨機初始化的方法

    TensorFlow中權(quán)重的隨機初始化的方法

    本篇文章主要介紹了TensorFlow中權(quán)重的隨機初始化的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-02-02
  • Python設(shè)計模式之代理模式實例

    Python設(shè)計模式之代理模式實例

    這篇文章主要介紹了設(shè)計模式中的代理模式Python實例,需要的朋友可以參考下
    2014-04-04
  • tensorflow訓(xùn)練中出現(xiàn)nan問題的解決

    tensorflow訓(xùn)練中出現(xiàn)nan問題的解決

    本篇文章主要介紹了tensorflow訓(xùn)練中出現(xiàn)nan問題的解決,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-02-02
  • Python的GUI編程之Pack、Place、Grid的區(qū)別說明

    Python的GUI編程之Pack、Place、Grid的區(qū)別說明

    這篇文章主要介紹了Python的GUI編程之Pack、Place、Grid的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06

最新評論