dr *_*bob 5 python django django-south
我正在尝试向现有应用程序执行django-south迁移以向其添加django-audit-log(以跟踪用户启动的模块更改),但遇到了重大错误.具体来说,action_user_id字段是LastUserField(存储指定正在跟踪的更改的用户).
如果我从空白模型开始,我可以通过以下方式添加audit_log:
from audit_log.models.managers import AuditLog
...
class SomeModel(models.Model)
...
audit_log = AuditLog()
Run Code Online (Sandbox Code Playgroud)
应用这个简单的更改并在django-south中进行模式迁移会给我一个错误:
! Cannot freeze field 'myapp.mymodelauditlogentry.action_user'
! (this field has class audit_log.models.fields.LastUserField)
! South cannot introspect some fields; this is probably because they are custom
! fields. If they worked in 0.6 or below, this is because we have removed the
! models parser (it often broke things).
! To fix this, read http://south.aeracode.org/wiki/MyFieldsDontWork
Run Code Online (Sandbox Code Playgroud)
我阅读了MyFieldsDontWork维基(以及自定义字段/内省部分),但它并不是100%清楚我需要做些什么来让字段工作.
我尝试添加:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^audit_log\.models\.fields\.LastUserField"])
Run Code Online (Sandbox Code Playgroud)
到我的models.py,它允许./manage.py架构迁移创建一个迁移脚本,之前的错误消失了.但是,当我尝试迁移(应用迁移)时,我收到以下错误:
Running migrations for myapp:
- Migrating forwards to 0004_auto__add_mymodelauditlogentry.
> my_app:0004_auto__add_mymodelauditlogentry
Traceback (most recent call last):
File "./manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.3-py2.6.egg/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.3-py2.6.egg/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.3-py2.6.egg/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.3-py2.6.egg/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.6/dist-packages/South-0.7.3-py2.6.egg/south/management/commands/migrate.py", line 105, in handle
ignore_ghosts = ignore_ghosts,
File "/usr/local/lib/python2.6/dist-packages/South-0.7.3-py2.6.egg/south/migration/__init__.py", line 191, in migrate_app
success = migrator.migrate_many(target, workplan, database)
File "/usr/local/lib/python2.6/dist-packages/South-0.7.3-py2.6.egg/south/migration/migrators.py", line 221, in migrate_many
result = migrator.__class__.migrate_many(migrator, target, migrations, database)
File "/usr/local/lib/python2.6/dist-packages/South-0.7.3-py2.6.egg/south/migration/migrators.py", line 292, in migrate_many
result = self.migrate(migration, database)
File "/usr/local/lib/python2.6/dist-packages/South-0.7.3-py2.6.egg/south/migration/migrators.py", line 125, in migrate
result = self.run(migration)
File "/usr/local/lib/python2.6/dist-packages/South-0.7.3-py2.6.egg/south/migration/migrators.py", line 93, in run
south.db.db.current_orm = self.orm(migration)
File "/usr/local/lib/python2.6/dist-packages/South-0.7.3-py2.6.egg/south/migration/migrators.py", line 246, in orm
return migration.orm()
File "/usr/local/lib/python2.6/dist-packages/South-0.7.3-py2.6.egg/south/utils.py", line 62, in method
value = function(self)
File "/usr/local/lib/python2.6/dist-packages/South-0.7.3-py2.6.egg/south/migration/base.py", line 422, in orm
return FakeORM(self.migration_class(), self.app_label())
File "/usr/local/lib/python2.6/dist-packages/South-0.7.3-py2.6.egg/south/orm.py", line 46, in FakeORM
_orm_cache[args] = _FakeORM(*args)
File "/usr/local/lib/python2.6/dist-packages/South-0.7.3-py2.6.egg/south/orm.py", line 125, in __init__
self.models[name] = self.make_model(app_label, model_name, data)
File "/usr/local/lib/python2.6/dist-packages/South-0.7.3-py2.6.egg/south/orm.py", line 318, in make_model
field = self.eval_in_context(code, app, extra_imports)
File "/usr/local/lib/python2.6/dist-packages/South-0.7.3-py2.6.egg/south/orm.py", line 236, in eval_in_context
return eval(code, globals(), fake_locals)
File "<string>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/django_audit_log-0.2.1-py2.6.egg/audit_log/models/fields.py", line 12, in __init__
super(LastUserField, self).__init__(User, null = True, **kwargs)
TypeError: __init__() got multiple values for keyword argument 'null'
Run Code Online (Sandbox Code Playgroud)
编辑(12/20中午):如果我将这些行添加到models.py,我可以应用schemamigration
from south.modelsinspector import add_introspection_rules, add_ignored_fields
add_ignored_fields(["^audit_log\.models\.fields\.LastUserField"])
Run Code Online (Sandbox Code Playgroud)
除了那么AUDIT_LOG中间件不起作用,因为在myapp_mymodelauditlogentry引用"AUTH_USER"的"ID"不action_user_id整型字段.然后我手动应用SQL(sqlite语法;通过在新创建的数据库上使用sqliteman获得.)
ALTER TABLE "myapp_mymodelauditlogentry" ADD "action_user_id" integer REFERENCES "auth_user" ("id");
Run Code Online (Sandbox Code Playgroud)
它的工作原理.如果有人在django-south的情况下解释我应该如何做迁移/内省,我还是会给予赏金,而不必去原始的数据库依赖SQL并且感激不尽.
另外,我为action_user_id创建了一个索引.我注意到模型的正常创建导致了一个名为的索引
CREATE INDEX "myapp_mymodelauditlogentry_26679921" ON "myapp_mymodelauditlogentry" ("action_user_id")
Run Code Online (Sandbox Code Playgroud)
我想知道哈希26679921是基于字段名称创建的,'%x' % (abs(hash(('action_user_id',))) % 4294967296L,)
并且不是基于其他任何东西(所以应始终为_26679921,除非数据库要求长名称被截断).我不确定索引的名字是否重要; 但是想要安全.
最后是答案(和解释).
迁移South时,不仅会存储模型中字段的名称,还会存储传递给它的类型和参数.结果是,南方必须了解哪些参数由字段给出以及哪些参数应该存储.
所以当你创建这样的规则时:
add_introspection_rules([], ["^audit_log\.models\.fields\.LastUserField"])
Run Code Online (Sandbox Code Playgroud)
Than South将创建一个包含如下列的表:
(
'action_user',
self.gf('audit_log.models.fields.LastUserField')(
related_name='_somemodel_audit_log_entry',
null=True,
to=orm['auth.User'],
)
),
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,related_name
参数,null
参数和to
参数都是如此.现在让我们来看看字段定义:
class LastUserField(models.ForeignKey):
"""
A field that keeps the last user that saved an instance
of a model. None will be the value for AnonymousUser.
"""
def __init__(self, **kwargs):
models.ForeignKey.__init__(self, User, null=True, **kwargs)
#print kwargs
#super(LastUserField, self).__init__(User, null = True, **kwargs)
def contribute_to_class(self, cls, name):
super(LastUserField, self).contribute_to_class(cls, name)
registry = registration.FieldRegistry(self.__class__)
registry.add_field(cls, self)
Run Code Online (Sandbox Code Playgroud)
我们在这看到什么?第一个参数ForeignKey
是user(第一个参数是to
属性).第二个参数(也是硬编码的)是null
参数.结果,当应用迁移时South
,您的字段将尝试设置这些参数.
你得到错误:
TypeError: __init__() got multiple values for keyword argument 'null'
Run Code Online (Sandbox Code Playgroud)
我们如何解决这个问题?
好吧,我们可以告诉South我们将这些参数作为默认值传递,以便它可以安全地忽略它们.
所以我们创建了一组这样的规则:
rules = [(
(fields.LastUserField,),
[],
{
'to': ['rel.to', {'default': User}],
'null': ['null', {'default': True}],
},
)]
add_introspection_rules(
rules,
['^audit_log\.models\.fields\.LastUserField'],
)
Run Code Online (Sandbox Code Playgroud)
因此,South现在了解如何存储参数以及需要忽略哪些参数.所以新的字段定义将是这样的:
(
'action_user',
self.gf('audit_log.models.fields.LastUserField')(
related_name='_somemodel_audit_log_entry'
)
),
Run Code Online (Sandbox Code Playgroud)
正如我们所看到的,related_name
还在这里,但to
和null
参数都消失了.所以现在我们可以安全地应用迁移而不会产生冲突.
小智 3
尽管使用了 @WoLpH 的答案中的步骤,我仍然无法创建迁移。我必须修改audit_log/models/fields.py 文件。我的 LastUserField 字段如下所示:
class LastUserField(models.ForeignKey):
"""
A field that keeps the last user that saved an instance
of a model. None will be the value for AnonymousUser.
"""
def __init__(self, **kwargs):
kwargs.pop('null', None)
kwargs.pop('to', None)
super(LastUserField, self).__init__(User, null = True, **kwargs)
def contribute_to_class(self, cls, name):
super(LastUserField, self).contribute_to_class(cls, name)
registry = registration.FieldRegistry(self.__class__)
registry.add_field(cls, self)
Run Code Online (Sandbox Code Playgroud)
在我不得不这样做之前,以下内容已添加到我的 models.py 文件中(该文件不起作用):
rules = [((fields.LastUserField,),
[],
{
'to': ['rel.to', {'default': User}],
'null': ['null', {'default': True}],
},)]
# Add the rules for the `LastUserField`
add_introspection_rules(rules, ['^audit_log\.models\.fields\.LastUserField'])
Run Code Online (Sandbox Code Playgroud)
关于如何避免这种黑客攻击,我有什么建议吗?
归档时间: |
|
查看次数: |
1819 次 |
最近记录: |