tortoise / tortoise/tortoise-orm
`ForeignKeyField`s `model` attribute refer to the last subclass in mixins
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 5.6k
- Forks
- 516
- Avg merge
- 2d 21h
- Merged PRs (30d)
- 9
Description
Describe the bug
It's impossible to use ForeignKeyFields in mixins. model attribute gets overwritten during metadata initialization each time mixin is subclassed.
To Reproduce
from tortoise import Model, fields
class ModelMixin:
id = fields.IntField(pk=True)
parent = fields.ForeignKeyField("models.SomeModel", related_name="children")
class SomeModel(Model, ModelMixin):
...
class AnotherModel(Model, ModelMixin):
...
print(f'{SomeModel.parent.model_name=}')
print(f'{SomeModel.parent.model=}')
print()
print(f'{AnotherModel.parent.model_name=}')
print(f'{AnotherModel.parent.model=}')
SomeModel.parent.model_name='models.SomeModel'
SomeModel.parent.model=<class '__main__.AnotherModel'>
AnotherModel.parent.model_name='models.SomeModel'
AnotherModel.parent.model=<class '__main__.AnotherModel'>
Expected behavior
One of the following:
ForeignKeyFields in mixins are supported: fields refer to the correct modelsForeignKeyFields in mixins are not supported: exception is raised when trying to use them, docs mention this limitation
Additional context
Python 3.9.1
tortoise_orm 0.16.20
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start at the metadata initialization path for ForeignKeyField and reproduce the mixin example, checking how model and model_name are assigned for each subclass. Trace the existing field and model registration tests, then add regression coverage for the chosen outcome: correct per-model references, or a clear failure and documentation if mixin relations are unsupported.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend, databases
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 32/100