Reputation: 9392
I am writing a app for django
which i am planning to publish. This app requires a Bolean
Setting variable CONSUMER_REGISTRATION
.
Aim of getting this variable is to decide whether to define ConsumerRegistrationModel
or not.
This is what I did.
from django.db import models
from django.conf import settings
if getattr(settings, 'CONSUMER_REGISTRATION', False):
class ConsumerRegistration(models.Model):
...
Its working fine. The only Issue i am facing that developers will need to run makemigrations and migrate commands each time they change the variable in settings.
1- Can this work be automated ?. So if they change the variable then some code in django auto run the makemigrations and migrate commands.
2- Or is it perfectly fine to leave this work on developers ??
3- Also I want to ask that is it a good aproach to do this in django ?
Upvotes: 3
Views: 627
Reputation: 15289
The accepted answer doesn't really provide a way to do what the OP is asking, which is to conditionally declare a model.
People may have various reasons for wanting to do this, from not declaring a model at all, to declaring models differently based on settings (it is implied that if you are doing this: you are intend to run the same code base in different places using different settings).
One solution is to put the model in its own app, and conditionally include the app based on a setting:
# Set this your per-project settings:
CONSUMER_REGISTRATION = True
# Set this in the generic settings
INSTALLED_APPS = [...]
if CONSUMER_REGISTRATION:
INSTALLED_APPS.append('consumer_registration') # Models will be loaded.
There's nothing wrong with creating an app which just contains a model.
With regards to "automating" it, the table will be created if migrations are run when the setting is true. It will not delete the table if it is changed to false.
Upvotes: 3
Reputation: 1579
You could simply define the model without any conditionals and tweak your app logic so that instances of ConsumerRegistration
model are only interacted with (i.e. created, updated etc.) when the 'CONSUMER_REGISTRATION'
flag is set to True
.
Running migrations every single time the value of 'CONSUMER_REGISTRATION'
is changed would make much more mess than leaving ConsumerRegistration
table empty.
As indicated by @dahrens, you could isolate the ConsumerRegistration
model along with relevant logic in a separate app, which would only be installed as needed by developers.
Upvotes: 2