I want the user to be able to select parameter values from an enum list of values as a dropdown in the swagger documentation.
The only way, to my knowledge, to do that is to create a Enum pydantic class, and designate a parameter as a part of that class. Which is fine. But in my situation, I want the enum to be dynamically generated based on all unique document values of a property stored in a MongoDB collection. I think you can create a BaseModel class dynamically using the create_model() function, but as far as I know that's not possible with a Enum class.
So my question is: How can I create a parameter enumeration in Swagger from all values in a mongDb collection?
In theory, you could create an enum dynamically with the functional API: https://docs.python.org/3/library/enum.html#functional-api
And then you could use that with Pydantic dynamic's create_model
with that dynamic enum.
I haven't personally tried it yet :sweat_smile: .
Nevertheless, if the possible values are "unbounded", if they can be a lot (stored in MongoDB), it might end up being better to use a frontend-side auto-completion widget, with search connected to the API, that then sends the query to MogoDB and keeps filtering the selectable values. Otherwise, you could have a very long select in the front end, that apart from looking ugly could make the browser unresponsive, etc.
I assume you solved your problem so I'll close this issue now. But feel free to add more comments or create new issues.
This came up on Google before any pydantic thread, so for anyone else looking it's surprisingly easy:
from pydantic import BaseModel
from enum import Enum
custom_enum_values = {
"cool": "stuff",
"other": "thing",
"foo": "fighters"
}
TypeEnum = Enum("TypeEnum", custom_enum_values)
class CustomModel(BaseModel):
type: TypeEnum = TypeEnum.cool
a = CustomModel()
print(a.type.name) # 'cool'
print(a.type.value) # 'stuff'
b = CustomModel(type="fighters")
print(f"{b.type.name.capitalize()} {b.type.value.capitalize()}") # 'Foo Fighters'
Most helpful comment
This came up on Google before any pydantic thread, so for anyone else looking it's surprisingly easy: