1

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

我没有找到任何选择。

例子:

对于 field Status,多个选项将是:

  • Active
  • Inactive
  • Locked

要选择的默认值是Active.

4

1 回答 1

0

如果您使用带枚举的类,这将有助于您的目标。以下适用于 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)
于 2019-08-28T09:08:38.670 回答