看看下面的元執行, 它增加了讀取權限到設置MyModelMeta類中的所有Django模型是thier 元類:
class MyModelMeta(ModelBase):
# add a read permission to each MyModelMeta model
def __new__(cls, name, bases, attrs):
Meta = None
if "Meta" in attrs:
Meta = attrs.get("Meta")
if hasattr(Meta, "abstract") and getattr(Meta, "abstract"):
# if the class is abstract, don't create permissions for it, just return the class object
return super(MyModelMeta, cls).__new__(cls, name, bases, attrs)
if not Meta:
# create a new Meta Class
Meta = type('Meta', (object,), {})
setattr(Meta, 'permissions',(("read_%s"%name.lower(), "Can read %s"%name.lower()),))
attrs['Meta'] = Meta
return super(MyModelMeta, cls).__new__(cls, name, bases, attrs)
創建一個抽象Django模型,並設置元類現在
class MyAbstractModel(models.Model):
__metaclass__ = MyModelMeta
class Meta:
abstract=True
,創建一個普通的Django模型,像這樣:memeber到MyModelMeta
class SomeModel(MyAbstractModel):
someFieldName = models.CharField(max_length=256, db_index=True)
這樣會生成默認的add/change/delete_somemodel權限,而且還會 它會添加一個新的read_somemodel權限。
如果您還使用南下,用此來產生額外的權限:
from django.db.models import get_app, get_models
from django.contrib.auth.management import create_permissions
create_permissions(get_app(app), get_models(), 2 if settings.DEBUG else 0)
「不工作」是指什麼?你能詳細說明嗎? – mawimawi 2010-06-03 11:20:09
請參閱編輯。我找不到任何文檔,如果這是應該工作或不... – 2010-06-03 11:26:03