Closed WizzyGeek closed 1 month ago
I got a similar error: name 'fields' is not defined
@abondar What's the purpose of this line: globalns = tortoise.Tortoise.apps.get(cls._meta.app, None) if cls._meta.app else None
, or how to fix this issue?
it's been a while I made the issue, but per my speculation, the rationale behind that seemed to be to allow using other models in the app inside annotations without imports? (which still is a questionable design choice imo)
I am not sure why it is there - but probably it is to support string typing notation, where you can make a link to other model, like you can do in ForeignKey
, just by string name. So probably it was aimed at that
I would say we can delete it, as it seems obscure and it is not design I want to promote
Seems that solution 1 is better. @WizzyGeek could you make a PR?
What Happened
Raises
Proposed Solution 1
https://github.com/tortoise/tortoise-orm/blob/53376c9032800770711f7a305ae971cba038b77f/tortoise/contrib/pydantic/utils.py#L17-L18
Removal of line 17 fixes the issue since the globalns goes back to the actual namespace of the object otherwise if this line is kept the namespace (both local and global) are replaced with the app namespace meaning the code for the annotations can only access models (afaik)
This solution changes behavior but I have not seen the current behavior documented or used anywhere yet.
Proposed Solution 2
Deal with internals of
typing.get_type_hints
and extend the globalns with app namespaceI can create a PR depending on which solution is preferred, there are also other ways if neither of the solutions are acceptable.
Workaround
Here is a DI ```python import tortoise def get_annotations(cls, method = None): return typing.get_type_hints(method or cls) tortoise.contrib.pydantic.utils.get_annotations = get_annotations tortoise.contrib.pydantic.creator.get_annotations = get_annotations ```