1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] How to make a field read-only in a `mongoengine` Document while allowing conditional...

Discussão em 'Python' iniciado por Stack, Setembro 12, 2024.

  1. Stack

    Stack Membro Participativo

    I have a mongoengine document such as:

    from mongoengine.document import Document
    from mongoengine import StringField

    class Class_A(Document):
    field_a = StringField()
    field_b = StringField()


    I'd like to lock field_b so it cannot be altered, e.g.

    var = <fetch Class_a document from DB>
    var.field = 'abc'


    would raise an error.

    This on itself is not a problem, but I'd like to be able to set field_b when field_a is set. To give an example, field_a could be some data and field_b would be computed hash for this data - user can set the data, but not the hash for it (it should be only set automatically when data is assigned).

    I tried using __setattr__/__dict__, but mongoengine seems to be doing some attributes magic behind the scene and I couldn't make it work. I also had an idea to subclass StringField and use a metaclass to wrap it's __setattr__, with similar effect.

    How to achieve such a behaviour?

    Continue reading...

Compartilhe esta Página