Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

defaut for created_date and updated_date #105

Open
jd-solanki opened this issue Feb 20, 2021 · 2 comments
Open

defaut for created_date and updated_date #105

jd-solanki opened this issue Feb 20, 2021 · 2 comments
Labels
enhancement New feature or request

Comments

@jd-solanki
Copy link

Feature request

I just discovered this I really love it ❤️

Context

I was testing FastAPI and came to odmantic as I am using mongoDB. I have a question regarding creating a model. How can I define a default value for created_date and updated_date? Is there any equivalent to Django'sDateField.auto_now_addandDateField.auto_now`

Solution

Something like Django have I guess if possible.

Alternative solutions

Using default_factory for created_date (I haven't tested it yet btw) and none for modified_date

Additional context

None.

Regards

@jd-solanki jd-solanki added the enhancement New feature or request label Feb 20, 2021
@carlosfrutos
Copy link

I just stumbled upon this question because I was having the same creation date in every object in my application:

So, if you use default to set the value, then you will always have the same value for every object instance:
creation_date: datetime = Field(default=datetime.now(), alias="creation_date", description="Task creation date")

To get the current date/datetime every time, you need to use default_factory with the datetime.now or datetime.date.today method call:
creation_date: datetime = Field(default_factory=datetime.now, description="Creation date")

Regards.

@troywilson
Copy link

troywilson commented Jul 24, 2024

I've been using:

from datetime import datetime, UTC
from odmantic import Field, Model
from pydantic import AwareDatetime
from pydantic.functional_validators import AfterValidator
from typing import Annotated, Any


def utc_now() -> datetime:
    return datetime.now(UTC)


def utc_now_validator(_: Any) -> Any:
    return utc_now()


UtcNowDatetime = Annotated[AwareDatetime, AfterValidator(utc_now_validator)]


class Example(Model):
    created_date: AwareDatetime = Field(default_factory=utc_now)
    modified_date: UtcNowDatetime = Field(default_factory=utc_now)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants