我有一个带有动态选择的模型,如果我可以保证在django-admin.py migrate / makemigrations命令事件下正在运行代码以防止其创建或警告无用的选择更改,那么我想返回一个空的选择列表。

代码:

from artist.models import Performance
from location.models import Location

def lazy_discover_foreign_id_choices():
    choices = []

    performances = Performance.objects.all()
    choices += {performance.id: str(performance) for performance in performances}.items()

    locations = Location.objects.all()
    choices += {location.id: str(location) for location in locations}.items()

    return choices
lazy_discover_foreign_id_choices = lazy(lazy_discover_foreign_id_choices, list)


class DiscoverEntry(Model):
    foreign_id = models.PositiveIntegerField('Foreign Reference', choices=lazy_discover_foreign_id_choices(), )

所以我想,如果我可以在lazy_discover_foreign_id_choices中检测到运行上下文,那么我可以选择输出一个空的选择列表。我当时正在考虑测试sys.argv__main__.__name__,但我希望有一种更可靠的方法或API?

最佳答案

我能想到的解决方案是在实际执行实际操作之前,将Django makemigrations命令子类化以设置标志。

示例:

将该代码放入<someapp>/management/commands/makemigrations.py,它将覆盖Django的默认makemigrations命令。

from django.core.management.commands import makemigrations
from django.db import migrations


class Command(makemigrations.Command):
    def handle(self, *args, **kwargs):
        # Set the flag.
        migrations.MIGRATION_OPERATION_IN_PROGRESS = True

        # Execute the normal behaviour.
        super(Command, self).handle(*args, **kwargs)

migrate命令执行相同的操作。

并修改您的动态选择功能:
from django.db import migrations


def lazy_discover_foreign_id_choices():
    if getattr(migrations, 'MIGRATION_OPERATION_IN_PROGRESS', False):
        return []
    # Leave the rest as is.

它很hacky,但是设置起来很容易。

10-05 18:53