2015-10-15 3 views
5

は、私は、ダイナミックな選択肢でモデルを持っているコマンドコードが移行のコンテキストで実行されているかどうかを検出し、私はコードがのイベントで実行されていることを保証できる場合は、空の選択リストを返したいですdjango-admin.py migrate/makemigrationsコマンドを使用して、無意味な選択肢の変更を作成または警告しないようにします。/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. 

それは非常にハックが、セットアップが非常に簡単です。

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

提案していただきありがとうございますが、これは動作しません。モデルフィールドの選択肢が 'Command.handle()の前に実行されているようだ。 – DanH

+0

私のプロジェクトでそれを試してみたところ、うまくいくように見えた。 – aumo

+0

@DanH Django 1.8.5のクリーンインストールで正常に動作することを確認します。デフォルトのコマンドではなく、実行される新しいコマンドであることを確信していますか? – aumo

4

は、ここで(Djangoはすでに私たちのためのフラグを作成するので)これを行うには、かなり非ハック方法です。

+0

これは本当にいいやり方です。 –

関連する問題