-
Notifications
You must be signed in to change notification settings - Fork 14
Fix read custom model id field #98
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
c68393f
to
0062d52
Compare
Codecov ReportAll modified and coverable lines are covered by tests ✅
Additional details and impacted files@@ Coverage Diff @@
## main #98 +/- ##
==========================================
+ Coverage 91.44% 91.63% +0.18%
==========================================
Files 44 44
Lines 2408 2414 +6
Branches 279 279
==========================================
+ Hits 2202 2212 +10
+ Misses 143 142 -1
+ Partials 63 60 -3
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
cls, | ||
session: AsyncSession, | ||
stmt: Select, | ||
resource_type: str, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Лучше делать методы по возможности идемпотентными. Тут запрос меняется в зависимости от состояния models_storage
Предлагаю передавать имя "id" поля в отдельном Optional аргументе как-нибудь так
@classmethod
async def count(
...,
id_field_name: Optional[str] = "id",
):
...
Подозреваю, что вызов count
всегда будет производиться с использованием того же resource_type
, с которым инстанцирован DataLayer
. Проверь пожалуйста этот момент и если это так нужно будет прокинуть id_field_name
в DataLayer
на этапе инстанцирования приложения и пользоваться этим значением
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ок, переделал:
- вынес получение
id_column_name
в базовый data layer - при вызове count передаю имя колонки
Теперь после инициализации data layer знает имя айди поля.
Data Layer инициализируется на каждый view заново, а View инициализируется на каждый запрос. DL привязывается к текущему view и работает с текущей сущностью
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Тут надо пойти ещё дальше и передавать id_field_name
на уровне view
https://github.com/mts-ai/FastAPI-JSONAPI/blob/fix/read-custom-model-id-field/fastapi_jsonapi/api/endpoint_builder.py#L216 для каждого эндпоинта.
На момент создания эндпоинтов ModelsStorage
содержит инфоррмацию по всем ресурсам, соответственно нет потребности вызывать его в рантайме.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
если мы из DataLayer вынесем в view, то внутри DL как обращаться?
Ты предлагаешь добавить при инициализации view, а мы это делаем на каждый запрос. и внутри view инициализируем DL - получается, что так, что так мы будем выставлять это значение
id_field_name=self.id_column_name, |
нужна ли доработка в итоге?
client: AsyncClient, | ||
age_rating_g: AgeRating, | ||
): | ||
url = app.url_path_for("get_age-rating_list") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В этом кейсе проверяем только случай, когда запрашиваем модель на верхнем уровне. Давай подойдем к решению бага комплексно, а именно нужны кейсы на
- запрос модели на верхнем уровне (этот случай)
- корректное поведение модели с кастомным id в качестве релейшеншипа/инклюда
- запрос модели через атомики
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
добавил создание с релейшном
создал отдельный тест на атомики
3fdaf94
to
c55ab22
Compare
+ other fixes + tests
29b6615
to
cc52512
Compare
) | ||
|
||
path: Union[str, list[str]] | ||
router: Optional[APIRouter] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Зачем?
When specifying custom model id field using
model_id_field_name
there's an 500 internal server error when getting list of entities.This PR fixes it using the provided
models_storage.get_model_id_field_name