我正在尝试向现有应用程序django-south migration添加django-audit-log(以跟踪用户启动的模块更改),但遇到了重大错误。具体来说,action_user_id字段是LastUserField(存储指定正在跟踪的更改的用户)。
如果我是从空白模型开始,我可以通过以下方式添加audit_log:
from audit_log.models.managers import AuditLog
...
class SomeModel(models.Model)
...
audit_log = AuditLog()
应用这个简单的更改并在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
我阅读了MyFieldsDontWork wiki(以及自定义字段/内省部分),但它并不是100%清楚我需要做些什么来让字段起作用。
我尝试添加:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^audit_log\.models\.fields\.LastUserField"])
到我的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'
编辑(12/20中午):如果我将这些行添加到models.py
,我可以应用schemamigrationfrom south.modelsinspector import add_introspection_rules, add_ignored_fields
add_ignored_fields(["^audit_log\.models\.fields\.LastUserField"])
除了audit_log中间件不起作用,因为myapp_mymodelauditlogentry中没有action_user_id整数字段引用“id”的“auth_user”。然后我手动应用SQL(sqlite语法;在新创建的数据库上使用sqliteman获得。)
ALTER TABLE "myapp_mymodelauditlogentry" ADD "action_user_id" integer REFERENCES "auth_user" ("id");
它有效。如果有人在django-south的情况下解释我应该如何做迁移/内省,我还是会给予赏金,而不必去原始的数据库依赖SQL并且感激不尽。
另外,我为action_user_id创建了一个索引。我注意到模型的正常创建导致了一个名为
的索引CREATE INDEX "myapp_mymodelauditlogentry_26679921" ON "myapp_mymodelauditlogentry" ("action_user_id")
我想知道哈希26679921是基于字段名'%x' % (abs(hash(('action_user_id',))) % 4294967296L,)
创建的,并且不是基于其他任何东西(所以应该始终是_26679921,除非数据库要求长名称被截断)。我不确定索引的名字是否重要;但是想要安全。
答案 0 :(得分:8)
最后是答案(和解释)。
迁移South时,不仅会存储模型中字段的名称,还会存储传递给它的类型和参数。结果是,南方必须了解该字段给出哪些参数以及应该存储哪些参数。
所以当你创建这样的规则时:
add_introspection_rules([], ["^audit_log\.models\.fields\.LastUserField"])
Than South将创建一个包含如下列的表:
(
'action_user',
self.gf('audit_log.models.fields.LastUserField')(
related_name='_somemodel_audit_log_entry',
null=True,
to=orm['auth.User'],
)
),
如您所见,其中包含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)
我们在这看到什么? ForeignKey
的第一个参数是user(第一个参数是to
属性)。第二个参数(也是硬编码的)是null
参数。结果是,在应用迁移时,South
和您的字段都会尝试设置这些参数。
你得到错误:
TypeError: __init__() got multiple values for keyword argument 'null'
我们如何解决这个问题?
好吧,我们可以告诉South我们将这些参数作为默认值传递,因此它可以安全地忽略它们。
所以我们创建了一组这样的规则:
rules = [(
(fields.LastUserField,),
[],
{
'to': ['rel.to', {'default': User}],
'null': ['null', {'default': True}],
},
)]
add_introspection_rules(
rules,
['^audit_log\.models\.fields\.LastUserField'],
)
因此,South现在了解如何存储参数以及需要忽略哪些参数。所以新的字段定义将是:
(
'action_user',
self.gf('audit_log.models.fields.LastUserField')(
related_name='_somemodel_audit_log_entry'
)
),
正如我们所看到的,related_name
仍在此处,但to
和null
参数已消失。所以现在我们可以安全地应用迁移而不会发生冲突。
答案 1 :(得分: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)
在我不得不采取行动之前,我的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'])
关于我可以做些什么来避免这种hackery的任何建议?