Open kevingill1966 opened 4 days ago
I found a discussion on this issue: #444
The authors:
from django.contrib.auth.models import Permission
from pprint import pp
from ninja import ModelSchema, Field
class PermissionSchema(ModelSchema):
content_type_id: int
class Meta:
model = Permission
fields = ['id', 'name', 'codename']
perm = Permission.objects.first()
serialiser = PermissionSchema.from_orm(perm)
d = serialiser.dict()
pp(d)
# {'content_type_id': 2, 'id': 5, 'name': 'Can add group', 'codename': 'add_group'}
This dictionary validates correctly
x = PermissionSchema.model_validate(d)
x.dict()
# {'content_type_id': 2, 'id': 5, 'name': 'Can add group', 'codename': 'add_group'}
Is this the standard approach or is there a more automated mechanism?
I want to write a CRUD style API. I retrieve the model data, and save the model data. I want to do that using the schema mapped from the Django Model.
When I try it, the schema serialises using the django model attribute name. However, the validator expects the _id suffix. I am looking for the recommended way to configure the ModelSchema below to generate a JSON version with the attribute "content_type_id", instead of "content_type".
Here is an example. Execute using "python manage.py shell"
If I move the field content_type to content_type_id, it can parse
Note - the property name in the schema is "content_type_id", but the generated output is "content_type"