django-ninja icon indicating copy to clipboard operation
django-ninja copied to clipboard

Schema is loading deferred properties

Open vitalik opened this issue 1 year ago • 6 comments

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.

vitalik avatar Nov 17 '23 09:11 vitalik

Sorry @vitalik, it seems like things are indeed working properly. This can be closed!

mustafa0x avatar Nov 20 '23 05:11 mustafa0x

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

mustafa0x avatar Nov 20 '23 05:11 mustafa0x

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

mustafa0x avatar Nov 20 '23 06:11 mustafa0x

Similar discussion: https://github.com/pydantic/pydantic/discussions/6861

mustafa0x avatar Nov 21 '23 06:11 mustafa0x

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.

mustafa0x avatar Nov 21 '23 15:11 mustafa0x

This overlaps with #333.

Also, I filed an issue in pydantic core https://github.com/pydantic/pydantic-core/issues/1095

mustafa0x avatar Dec 12 '23 02:12 mustafa0x