Determine if code is running in the context of the migrate / makemigrations command

I have a model with dynamic options, and I would like to return an empty selection list if I can guarantee that the code is executed in the case of the django-admin.py migrate / makemigrations to prevent it from being generated or a warning about a useless change selection.

code:

 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(), ) 

So, I would think that if I can detect the startup context in lazy_discover_foreign_id_choices , then I can select the output of an empty selection list. I was thinking about testing sys.argv and __main__.__name__ , but I hope a more reliable way or API is possible?

+5
source share
2 answers

The solution I can think of is to subclass the Django makemigrations to set a flag before actually executing the actual operation.

Example:

Put this code in <someapp>/management/commands/makemigrations.py , it will override the default makemigrations 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) 

Do the same for the migrate command.

And change the dynamic selection function:

 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. 

These are very hacks, but quite easy to configure.

+2
source

Here's a pretty awkward way to do this (since django already creates flags for us):

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

This should work for all cases.

+5
source

Source: https://habr.com/ru/post/1233764/


All Articles