怎么在Django中實(shí)現(xiàn)多數(shù)據(jù)庫-創(chuàng)新互聯(lián)

本篇文章為大家展示了怎么在Django中實(shí)現(xiàn)多數(shù)據(jù)庫,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

成都網(wǎng)站制作、成都網(wǎng)站建設(shè)、外貿(mào)營銷網(wǎng)站建設(shè)介紹好的網(wǎng)站是理念、設(shè)計(jì)和技術(shù)的結(jié)合。成都創(chuàng)新互聯(lián)擁有的網(wǎng)站設(shè)計(jì)理念、多方位的設(shè)計(jì)風(fēng)格、經(jīng)驗(yàn)豐富的設(shè)計(jì)團(tuán)隊(duì)。提供PC端+手機(jī)端網(wǎng)站建設(shè),用營銷思維進(jìn)行網(wǎng)站設(shè)計(jì)、采用先進(jìn)技術(shù)開源代碼、注重用戶體驗(yàn)與SEO基礎(chǔ),將技術(shù)與創(chuàng)意整合到網(wǎng)站之中,以契合客戶的方式做到創(chuàng)意性的視覺化效果。

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

比如要使用兩個(gè)數(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個(gè)數(shù)據(jù)庫,別名一個(gè)為default,一個(gè)為user。數(shù)據(jù)庫的別名可以任意確定。

default的別名比較特殊,一個(gè)Model在路由中沒有特別選擇時(shí),默認(rèn)使用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'
  }
}

這樣,因?yàn)闆]有了默認(rèn)的數(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用來確定一個(gè)Model使用哪一個(gè)數(shù)據(jù)庫,主要定義以下四個(gè)方法:

db_for_read(model, **hints)

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

db_for_write(model, **hints)

規(guī)定model使用哪一個(gè)數(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ù)庫上運(yùn)行。

一個(gè)完整的例子:

數(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',
  },
}

如果想要達(dá)到如下效果:

app_label為auth的Model讀寫都在auth_db中完成,其余的Model寫入在primary中完成,讀取隨機(jī)在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ù)庫中可以運(yùn)行。

其余的:

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

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

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

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

就可以了。

進(jìn)行migrate操作時(shí):

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

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

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

也可以手動(dòng)的選擇路由:

查詢:

>>> # 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')

移動(dòng):

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

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

有兩個(gè)解決方法;

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)

刪除:

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

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

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

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

上述內(nèi)容就是怎么在Django中實(shí)現(xiàn)多數(shù)據(jù)庫,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

網(wǎng)站名稱:怎么在Django中實(shí)現(xiàn)多數(shù)據(jù)庫-創(chuàng)新互聯(lián)
當(dāng)前路徑:http://bm7419.com/article18/dpcogp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站營銷、品牌網(wǎng)站制作、定制開發(fā)、企業(yè)網(wǎng)站制作App開發(fā)、虛擬主機(jī)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

商城網(wǎng)站建設(shè)