Search code examples
flaskpymongoflask-pymongo

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


Since I am new to flask-pymongo. I want to design my database such that there are a few specific multiple options out of which one is chosen to be the default value. How do I do that?

I did not find any option to do that.

Example:

For the field Status, multiple options would be:

  • Active
  • Inactive
  • Locked

The default value to be chosen would be Active.


Solution

  • If you use classes with enumerations, this will aid your goal. The following works in Python 3.7. The nice thing is you can add to the Options list easily without having to rework any code.

    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)