因为我是flask-pymongo的新手。我想设计我的数据库,以便有几个特定的多个选项,其中一个被选择为默认值。我该怎么做?
我没有任何选择去做这件事。
示例:
对于字段Status,多个选项是:
ActiveInactiveLocked要选择的默认值是Active。
发布于 2019-08-28 09:08:38
如果您在枚举中使用类,这将有助于您的目标。下面是Python3.7中的功能。更好的是,您可以轻松地添加到选项列表中,而无需重做任何代码。
from typing import Optional
from enum import Enum
from time import sleep
from pymongo import MongoClient
connection = MongoClient('localhost', 27017)
db = connection['yourdatabase']
# Define the enumerated list of options
class Options(Enum):
ACTIVE = 'Active'
INACTIVE = 'Inactive'
LOCKED = 'Locked'
# Define the class for the object
class StockItem:
def __init__(self, stock_item, status = None) -> None:
self.stock_item: str = stock_item
self.status: Optional[Options] = status
# Check if the status is set; if not set it to the default (Active)
if self.status is None:
self.status = Options.ACTIVE
# Check the status is valid
if self.status not in Options:
raise ValueError (f'"{str(status)}" is not a valid Status')
# The to_dict allows us to manipulate the output going to the DB
def to_dict(self) -> dict:
return {
"StockItem": self.stock_item,
"Status": self.status.value # Use status.value to get the string value to store in the DB
}
# The insert is now easy as we've done all the hard work earlier
def insert(self, db) -> None:
db.stockitem.insert_one(self.to_dict())
# Note item 2 does note have a specific status set, this will default to Active
item1 = StockItem('Apples', Options.ACTIVE)
item1.insert(db)
item2 = StockItem('Bananas')
item2.insert(db)
item3 = StockItem('Cheese', Options.INACTIVE)
item3.insert(db)
item4 = StockItem('Dog Food', Options.LOCKED)
item4.insert(db)
for record in db.stockitem.find({}, {'_id': 0}):
print (record)
# The final item will fail as the status is invalid
sleep(5)
item5 = StockItem('Eggs', 'Invalid Status')
item5.insert(db)https://stackoverflow.com/questions/57680235
复制相似问题