首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在创建文档时从几个选项中选择一个默认选项?

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

Stack Overflow用户
提问于 2019-08-27 18:16:36
回答 1查看 32关注 0票数 1

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

我没有任何选择去做这件事。

示例:

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

  • Active
  • Inactive
  • Locked

要选择的默认值是Active

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-28 09:08:38

如果您在枚举中使用类,这将有助于您的目标。下面是Python3.7中的功能。更好的是,您可以轻松地添加到选项列表中,而无需重做任何代码。

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57680235

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档