[Python] MongoEngine library doesn't allow to use its BaseFields for persisting data

Discussão em 'Python' iniciado por Stack, Janeiro 23, 2025.

  1. Stack

    Stack Membro Participativo

    I started to use mongoengine library in order to read and write data from Mongo DB.

    I found some strage behavior. The following class is defined in my codebase:

    class CustomerRequest(BaseModel):
    type = fields.EnumField(RequestType)
    status = fields.EnumField(Status, default=Status.NEW)
    request_date = fields.DateField(db_field='requestDate')


    I created an object of type CustomerRequest:

    customer_request = CustomerRequest(type=Type.complaints, status=Status.Opened, request_date=DateTimeField("2023-03-01 00:00:00")


    and then I persisted customer_request using mongoengine library:

    customer_request.save()


    After executing this line, I got the error:


    Validation Failed: cannot parse date "<mongoengine.fields.datetimefield...>"
    ​

    However, I found that if I create a CustomerRequest object with a "regular" datatime Python object:

    customer_request = CustomerRequest(type=Type.complaints, status=Status.Opened, request_date=datetime("2023-03-01 00:00:00"))


    Then, persistance goes well without any error.

    I don't understand why CustomerRequest defines request_date as field of type DateTimeField, but expects this field to be of type datetime in order to persist it. Should I define two different classes for CustomerRequest? one that describes the data in the database, and a second that describes the object in Python code?

    Continue reading...

Compartilhe esta Página