django-ninja
django-ninja copied to clipboard
Schema is loading deferred properties
Discussed in https://github.com/vitalik/django-ninja/discussions/928
Originally posted by mustafa0x November 17, 2023
class File(Schema):
id: int
text: str | None = None
@router.get('/file/{file_id}/', response=File, exclude_unset=True)
def get_file(request: ASGIRequest, file_id: int):
return File.objects.only(('id',)).get(id=file_id)
The response includes the text, even though I excluded/deferred it using only
.
Sorry @vitalik, it seems like things are indeed working properly. This can be closed!
Ok, I apologize again, things are indeed not working as originally reported.
The following line is what triggers instance.refresh_from_db(fields=[field_name])
in django.
https://github.com/vitalik/django-ninja/blob/6f27eeef965f15091b7f51a2a9f4d5eef275f674/ninja/schema.py#L65
Something like this should be a good solution. It might need to be made opt-in, to avoid a breaking change.
if key in self._obj.get_deferred_fields():
# skip field
Similar discussion: https://github.com/pydantic/pydantic/discussions/6861
https://github.com/pydantic/pydantic/issues/8192
Lazy loaded orm fields are loaded inadvertently by model_validate. I'd like to be able to exclude fields from model_validate.
This overlaps with #333.
Also, I filed an issue in pydantic core https://github.com/pydantic/pydantic-core/issues/1095