Use property to alias ForeignKey fields instead of Pydantic alias #1111
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #828 and helps with #469. Full explanation here. Apologies if this explanation isn't quite clear, I'm definitely struggling to explain this properly lol.
Currently for ModelSchema, Ninja uses Pydantic aliases to alias between a ForeignKey field's property name as defined by the user, and the attribute name which holds the ID referenced by the foreign key (
author
vsauthor_id
). However, this prevents users from using Pydantic'salias_generator
with ForeignKey field names.This PR removes the alias and then changes the property name on the Pydantic model to match the attribute name on the Django model (
author_id
), which should allow for data dumped out withmy_schema.model_dump()
to still correctly match up to Django fields as it does now. It then addsproperty
fields to alias between the attribute name and the property name, so any accesses on the model, likemy_schema.author
, will get aliased to the real property name,my_schema.author_id
.Let me know if there are any changes I need to make. I'm going to also write some tests to polish this off.