How to put updated_at in UserUpdate #1498
-
Hi, I'm wondering how I can automatically set the field updated_at when there is an update in the User. models.py class User(BeanieBaseUser, Document):
id: UUID = Field(alias="_id", default_factory=uuid4)
first_name: str = Field(title="First Name", description="The first name of the user", max_length=50)
last_name: str = Field(title="Last Name", description="The last name of the user", max_length=50)
is_recruiter: bool = Field(title="Is Recruiter", description="If the user is recruiter", default=False)
created_at: datetime = Field(title="Created At", description="The date when the user was created", default_factory=lambda: datetime.now(timezone.utc))
updated_at: datetime = Field(title="Updated At", description="The date when the user was updated", default_factory=lambda: datetime.now(timezone.utc)) schemas.py class UserUpdate(schemas.BaseUserUpdate):
first_name: Optional[str] = None
last_name: Optional[str] = None
# FIXME how can I automatically set the updated_at field?
updated_at: datetime = Field(default=lambda: datetime.now(timezone.utc))
@field_validator("first_name")
@classmethod
def validate_first_name(cls, value):
if len(value) > 50:
raise ValueError("First name must be less than 50 characters")
return value
@field_validator("last_name")
@classmethod
def validate_last_name(cls, value):
if len(value) > 50:
raise ValueError("Last name must be less than 50 characters")
return value I tried in several ways, setting straight the value, put only a lambda function. Regarding the validation, is it correct doing in the schemas? I added it because without it, I'm getting InternalServerError if the length of first_name > 50 (as set in the model) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
After using ChatGpt i found the solution straight with Beanie, I added this to my model: class User(BeanieBaseUser, Document):
id: UUID = Field(alias="_id", default_factory=uuid4)
first_name: str = Field(title="First Name", description="The first name of the user", max_length=50)
last_name: str = Field(title="Last Name", description="The last name of the user", max_length=50)
is_recruiter: bool = Field(title="Is Recruiter", description="If the user is recruiter", default=False)
created_at: datetime = Field(title="Created At", description="The date when the user was created", default_factory=lambda: datetime.now(timezone.utc))
updated_at: datetime = Field(title="Updated At", description="The date when the user was updated", default_factory=lambda: datetime.now(timezone.utc))
@before_event(ValidateOnSave)
async def set_updated_at(self):
self.updated_at = datetime.now(timezone.utc) Source: https://beanie-odm.dev/tutorial/event-based-actions/ I leave the question open if there will be any advice regarding the validation in the schema |
Beta Was this translation helpful? Give feedback.
After using ChatGpt i found the solution straight with Beanie, I added this to my model: