创建文档时如何从几个选项中选择一个默认选项?

How to choose a default option out of few multiple options while creating document?

因为我是 flask-pymongo 的新手。我想设计我的数据库,以便有一些特定的多个选项,其中一个被选为默认值。我该怎么做?

我没有找到任何选项。

Example:

对于字段 Status,多个选项为:

要选择的默认值为 Active

如果您将 类 与枚举一起使用,这将有助于您实现目标。以下适用于 Python 3.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)