Django 迁移中不存在的 Mixin 字段
Mixin fields not existing on Django migrations
假设我有这样的混合:
class Test(object):
...some logic...
class TestMixin(models.Model):
db_field = django database field
test = Test() # not a database field
class Meta:
abstract = True
class Foo(TestMixin, models.Model):
... more db fields ...
我遇到了一个奇怪的问题。如果我通过 django shell 检查 Foo,我可以看到两个字段,db_field 和 test
但是如果我创建这个迁移:
from __future__ import unicode_literals
from django.db import migrations
def custom_operation(apps, schema_editor):
Foo = apps.get_model('django_app', 'Foo')
stuffs = Foo.objects.all()
for stuff in stuffs:
print stuff.test # this doesnt exist
class Migration(migrations.Migration):
dependencies = [
...
]
operations = [
migrations.RunPython(custom_operation),
]
如果我在 Test() __init__
添加断点,它会通过 shell 或 Django 调用,但不会在 运行 迁移时调用。
通过迁移使用模型有什么区别?
https://docs.djangoproject.com/en/1.11/topics/migrations/#historical-models
特别是这句话:
Because it’s impossible to serialize arbitrary Python code, these historical models will not have any custom methods that you have defined. They will, however, have the same fields, relationships, managers (limited to those with use_in_migrations = True) and Meta options (also versioned, so they may be different from your current ones).
假设我有这样的混合:
class Test(object):
...some logic...
class TestMixin(models.Model):
db_field = django database field
test = Test() # not a database field
class Meta:
abstract = True
class Foo(TestMixin, models.Model):
... more db fields ...
我遇到了一个奇怪的问题。如果我通过 django shell 检查 Foo,我可以看到两个字段,db_field 和 test
但是如果我创建这个迁移:
from __future__ import unicode_literals
from django.db import migrations
def custom_operation(apps, schema_editor):
Foo = apps.get_model('django_app', 'Foo')
stuffs = Foo.objects.all()
for stuff in stuffs:
print stuff.test # this doesnt exist
class Migration(migrations.Migration):
dependencies = [
...
]
operations = [
migrations.RunPython(custom_operation),
]
如果我在 Test() __init__
添加断点,它会通过 shell 或 Django 调用,但不会在 运行 迁移时调用。
通过迁移使用模型有什么区别?
https://docs.djangoproject.com/en/1.11/topics/migrations/#historical-models
特别是这句话:
Because it’s impossible to serialize arbitrary Python code, these historical models will not have any custom methods that you have defined. They will, however, have the same fields, relationships, managers (limited to those with use_in_migrations = True) and Meta options (also versioned, so they may be different from your current ones).