创建从ForeignKey继承的自定义字段并设置to字段时,存在解构问题。
简化示例(models.py)
from django.db import models
from django.contrib.auth.models import User
class UserField(models.ForeignKey):
def __init__(self, *args, **kwargs):
kwargs['to'] = User
super(UserField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(UserField, self).deconstruct()
del kwargs['to']
return name, path, args, kwargs
class FooBar(models.Model):
user = UserField()
当python manage.py makemigrations
引发以下异常时。
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemigrations.py", line 111, in handle
convert_apps=app_labels or None,
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/autodetector.py", line 40, in changes
changes = self._detect_changes(convert_apps, graph)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/autodetector.py", line 139, in _detect_changes
self.generate_renamed_models()
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/autodetector.py", line 413, in generate_renamed_models
model_fields_def = self.only_relation_agnostic_fields(model_state.fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/autodetector.py", line 79, in only_relation_agnostic_fields
del deconstruction[2]['to']
KeyError: u'to'
可以通过在解构过程中不删除'to'kwarg来解决,但是,这显然会在构造函数中留下不需要的'to'kwarg,如下所示:
from django.db import models, migrations
from django.conf import settings
import bar.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='FooBar',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('user', bar.models.UserField(to=settings.AUTH_USER_MODEL)),
],
options={
},
bases=(models.Model,),
),
]
我已经尝试了一些变体(例如将User作为超级调用的第一个arg),但是,结果大致相同或产生其他问题。有没有更好/不同的方法来正确实现这样的自定义字段的迁移支持?