淺析django的abstract,proxy, managed

 

                  django.db.models.Model 的 Meta參數python

參數 類型 說明 繼承
abstract boolean 是否建表 不繼承,子類自動充值爲默認值(False)
managed boolean 是否自動建表 不繼承,子類自動充值爲默認值(True)
proxy boolean 是否爲代理類(不建表) 不繼承,子類自動充值爲默認值(False)

 

 

 

 

 

 

1
2
3
4
5
6
7
class Author(models.Model):
     first_name = models.CharField(max_length = 30 )
     last_name = models.CharField(max_length = 40 )
     email = models.EmailField(blank = True ,verbose_name = 'e-mail' )
 
     def __unicode__( self ):
         return u '%s %s' % ( self .first_name, self .last_name)

代理類 AuthorProxysql

1
2
3
class AuthorProxy(Author):
     class Meta:
         proxy = True

代理類子類 AuthorProxy2數據庫

1
2
class AuthorProxy2(AuthorProxy):
     pass

經過sqlall查看(django 1.6.5),建表以下:django

1
2
3
CREATE TABLE "books_authorproxy2" (
     "author_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "books_author" ( "id" ) DEFERRABLE INITIALLY DEFERRED
);

 

所以,能夠判定,proxy在繼承中的特性跟abstract同樣。post

將以上代碼中的proxy換成managed ,並設置爲 False,經測試,生成sql以下:測試

1
2
3
CREATE TABLE "books_authorproxy2" (
     "authorproxy_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "books_authorpoxy" ( "author_ptr_id" ) DEFERRABLE INITIALLY DEFERRED
);

即,managed不會繼承到子類,子類會默認重置爲Truespa

 

用途

proxy or managed?

官方是這麼說的:代理

So, the general rules are:code

1. If you are mirroring an existing model or database table and don’t want all the original database table columns, use Meta.managed=False. That option is normally useful for modeling database views and tables not under the control of Django.
2. If you are wanting to change the Python-only behavior of a model, but keep all the same fields as in the original, use Meta.proxy=True. This sets things up so that the proxy model is an exact copy of the storage structure of the original model when data is saved.orm

即,一般:

1. 若是你要映射模型到已經存在的數據庫,使用managed=False, 這適合不在django控制之下的數據庫表和視圖。

2. 若是隻想要給模型修改python行爲,而不須要改變任何字段,使用 proxy=True, 這會保持模型類的數據跟原始表結構同樣(實際上就是一個表)

abstract

基本上,父類(abstract)的字段會拷貝到子類的每個表中(若是子類沒有設置Meta.abstract=True), 所以適合的情形,好比給全部表增長一些共性字段,好比建立人等信息。

相關文章
相關標籤/搜索