简体   繁体   English

有条件的Django模型创建

[英]Conditional Django Model Creation

I am writing a app for django which i am planning to publish. 我正在为django编写一个我打算发布的应用程序。 This app requires a Bolean Setting variable CONSUMER_REGISTRATION . 此应用需要Bolean设置变量CONSUMER_REGISTRATION

Aim of getting this variable is to decide whether to define ConsumerRegistrationModel or not. 获取此变量的目的是决定是否定义ConsumerRegistrationModel

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. 我面临的唯一问题是,开发人员每次更改设置变量时都需要运行makemigrations和迁移命令。

1- Can this work be automated ? 1-这项工作可以自动化吗? . So if they change the variable then some code in django auto run the makemigrations and migrate commands. 因此,如果他们更改了变量,那么django中的一些代码会自动运行makemigrations和migration命令。

2- Or is it perfectly fine to leave this work on developers ?? 2-还是将这项工作留给开发人员完全可以吗?

3- Also I want to ask that is it a good aproach to do this in django ? 3-另外我想问一问,在Django中这样做是一个好方法吗?

You could simply define the model without any conditionals and tweak your app logic so that instances of ConsumerRegistration model are only interacted with (ie created, updated etc.) when the 'CONSUMER_REGISTRATION' flag is set to True . 您可以简单地定义模型而没有任何条件,并调整应用程序逻辑,以便仅当'CONSUMER_REGISTRATION'标志设置为True时, ConsumerRegistration模型的实例才与(例如,创建,更新等)进行交互。

Running migrations every single time the value of 'CONSUMER_REGISTRATION' is changed would make much more mess than leaving ConsumerRegistration table empty. 每次更改'CONSUMER_REGISTRATION'的值都运行迁移,比将ConsumerRegistration表保留为空会造成更多的混乱。

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. 如@ dahrens所示 ,您可以在一个单独的应用程序中隔离ConsumerRegistration模型以及相关逻辑,该应用程序仅在开发人员需要时才安装。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM