odmantic icon indicating copy to clipboard operation
odmantic copied to clipboard

Allow forwardRefs

Open SolAstri opened this issue 3 years ago • 3 comments

I have a code like this:

from odmantic import Field, Model, EmbeddedModel, Reference
from typing import List

class Revision(EmbeddedModel):
    modified_by: "User" = Reference()

class User(Model):
    revisions: List[Revision]

It yields this error:

Traceback (most recent call last):
  File "..../api/m_example.py", line 4, in <module>
    class Revision(EmbeddedModel):
  File ".../lib/python3.8/site-packages/odmantic/model.py", line 443, in __new__
    mcs.__validate_cls_namespace__(name, namespace)
  File .../lib/python3.8/site-packages/odmantic/model.py", line 290, in __validate_cls_namespace__
    parse_obj_as(field_type, value)
  File "pydantic/tools.py", line 35, in pydantic.tools.parse_obj_as
  File "pydantic/main.py", line 360, in pydantic.main.BaseModel.__init__
  File "pydantic/main.py", line 955, in pydantic.main.validate_model
pydantic.errors.ConfigError: field "__root__" not yet prepared so type is still a ForwardRef, you might need to call ParsingModel[ForwardRef('User')].update_forward_refs().

SolAstri avatar Nov 26 '20 09:11 SolAstri

Yes actually calling update_forward_refs() would be needed while initializing the model.

However, it would allow to create cyclic references. This is currently not handled as the references are eager for now

art049 avatar Nov 30 '20 18:11 art049

Is it possible to make cyclic references now?

SolAstri avatar Jun 04 '21 16:06 SolAstri

In my self-referential model case even update_forward_refs not working. It's look something like following

from __future__ import annotations

class Task(Model):
    source_task: Task = Reference()

Task.update_forward_refs()

If I am removing = Reference() then its working fine.

gagandeep avatar Sep 05 '21 21:09 gagandeep