I have the following User
class
class User(db.Model, CommonFields):
__tablename__ = "user"
__table_args__ = {"schema": "metadata"}
email = db.Column(db.String)
name = db.Column(db.String
client = db.relationship("Clients", secondary=client_group)
I am inserting into the DB during the following function
def create_user(
email: str,
name: str,
client_group: str
):
client_group = Client.get_client(client_group)
if client_group:
user = User(
email=email,
name=name,
client=[client_group]
)
else:
user = User(
email=email,
name=name,
)
user = user.insert()
return user_schema.dump(user)
Now this works, but it's very repetitive.
My question is there a way to do this to make it less repetitive?
A way to have conditional class arguments without repeating it in an if statement?
CodePudding user response:
You can use a dictionary to pass named parameters dynamically. Then you can conditionally add an item to the dictionary.
user_dict = {"email": email, "name": name}
if client_group:
user_dict["client"] = [client_group]
user = User(**user_dict)