2015-10-15 47 views
5

我有一个具有动态选择的模型,并且我想返回一个空的选择列表,如果我可以保证代码在发生django-admin.py migrate/makemigrations命令来阻止它创建或警告无用的选择更改。检测代码是否在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?

+1

你的选择如何动态?你可以发布一些代码吗? – aumo

+0

当然,代码增加了 – DanH

+0

如何导入'Performance'和'Location'? – Ivan

回答

2

我能想到的解决方案是在实际执行实际操作之前,将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. 

这是非常哈克,但很容易设置。

+0

感谢您的建议,但这是行不通的。似乎模型字段的选择是在'Command.handle()' – DanH

+0

之前执行的,我在我的一个项目上试过了,它似乎工作,我会调查。 – aumo

+0

@DanH我确认它在干净的Django 1.8.5安装中工作正常,你确定它是被执行的新命令,而不是默认的吗? – aumo

4

这里是要做到这一点(因为Django的已经为我们创造的标志)相当不哈克的方式:

import sys 
def lazy_discover_foreign_id_choices(): 
    if ('makemigrations' in sys.argv or 'migrate' in sys.argv): 
     return [] 
    # Leave the rest as is. 

这应该为所有情况下工作。

+0

哦,这是一个非常好的方法来做到这一点。 –

相关问题