【发布时间】:2020-08-18 05:04:45
【问题描述】:
根据django docs,在模型中处理选择字段的最佳方法是这样做:
class Book(models.Model):
AVAILABLE = 'available'
BORROWED = 'borrowed'
ARCHIVED = 'archived'
STATUS = [
(AVAILABLE, 'Available to borrow'),
(BORROWED, 'Borrowed by someone'),
(ARCHIVED, 'Archived - not available anymore'),
]
# […]
status = models.CharField(
max_length=32,
choices=STATUS,
default=AVAILABLE,
)
但是,我的应用增长了很多,并且扩展了不同应用之间的模型互连。在某些情况下,我需要导入模型类只是为了使用常量值
例如:
# some other file
from book.models import Book
def do_stuff_if_borrowed(book):
if (book.status == Book.BORROWED):
# do stuff
pass
我想尽可能避免在其他文件中导入模型,因为它会导致很多循环导入问题,总的来说我觉得这不是最干净的方法。我快速查了一下,没有人提出如何将这些模型常量外部化的解决方案,例如:
book/constants.py
AVAILABLE = 'available'
BORROWED = 'borrowed'
ARCHIVED = 'archived'
STATUS = [
(AVAILABLE, 'Available to borrow'),
(BORROWED, 'Borrowed by someone'),
(ARCHIVED, 'Archived - not available anymore'),
]
book/models.py
from .constants import STATUS, AVAILABLE
class Book(models.Model):
status = models.CharField(
max_length=32,
choices=STATUS,
default=AVAILABLE,
)
然后如果我只需要常量,我不需要导入 Book 模型,而只需要导入 constants.py
有理由不这样做吗?
【问题讨论】:
-
我认为唯一的原因是您可以使用常用词
AVAILABLEARCHIVED已经在您的其他模型中使用,我认为您应该考虑让名称更独特,例如BOOK_STATUS_AVAILABLE@ 987654329@,所以你不会对重复的名字感到困惑 -
是的,这将使常量独一无二
标签: django django-models python-import