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
Foreign key field value instead of id without nesting schemas ? #291
Comments
You can nested class DepartmentOut(Schema):
dep: str
class StudentOut(DepartmentOut):
id: int
name: str |
class Student(models.Model):
...
@property
def dep_name(self):
return self.dep.dep
class StudentOut(Schema):
id: int
name: str
dep_name: str
# or dep: str = Field(..., alias='dep_name') |
Thanks a million to you guys. I thought there might be an internal other thing for that matter. Very appreciated and excuse me for taking your time. |
Maybe helpful. I don't tested this. from functools import reduce
from pydantic.utils import GetterDict as GetterDictOrigin
def nested_getattr(obj: object, attr: str, *args):
def _getattr(obj, attr):
return getattr(obj, attr, *args)
return reduce(_getattr, [obj] + attr.split('.'))
class GetterDict(GetterDictOrigin):
def __getitem__(self, key: str) -> Any:
try:
return nested_getattr(self._obj, key)
except AttributeError as e:
raise KeyError(key) from e
def get(self, key: Any, default: Any = None) -> Any:
return nested_getattr(self._obj, key, default)
class StudentOut(Schema):
id: int
name: str
dep: str = Field(..., alias='dep.dep')
class Config:
getter_dict = GetterDict
orm_mode = True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, is it possible to send a foreign key value without nesting the schemas ? Here's my scenario:
this will result in an output of:
How can I show the dep string without a nested object called dep? Like the below shape of JSON:
I tried searching without any luck, thanks in advance.
The text was updated successfully, but these errors were encountered: