django-ninja
django-ninja copied to clipboard
Support django model type annotations
Hey 👋
First, thanks a lot for this lib! It really helped us deliver better quality software.
We are developing a (close to) fully typed application using Django. In lots of models we explicitly specify the type of the fields when the basic type is not precise enough, for example:
TaskStatus = Literal["todo", "done"]
class TaskConfiguration(TypedDict):
foo: int
bar: str
class Task(models.Model):
status: TaskStatus = models.CharField()
configuration: TaskConfiguration = models.JSONField()
The issue arises when we define the associated Pydantic models, we have to redefine the types for those fields:
class TaskSchema(ModelSchema):
status: TaskStatus
configuration: TaskConfiguration
class Meta:
model = Task
fields = "__all__"
This PR makes ModelSchema aware of the type annotations and allow the previous schema to be defined as
class TaskSchema(ModelSchema):
class Meta:
model = Task
fields = "__all__"
... so we are not repeating the type and avoid runtime errors when there is a Django model/Pydantic model mismatch.
This is a draft that would require more work/testing, let me know if you think this is an idea worth pursuing.
Cheers!
Hi @rchoquet
Looks good
- Could you also add some docs / examples-to-documentation
- and to support python3.8/3.7 I think you need to import Literal from typing_extensions
I'll add the doc+examples asap
@vitalik should be good now.
Hi @rchoquet looks good
could you also add docs example with JsonField - as this is actually a pretty often question
Question: is this common to type your fields instead of using django-stubs? Also, if you support this, are you going to support stubs in general?
Question: is this common to type your fields instead of using django-stubs?
I don't know, but I think you have to if you want more than the primitive types (ex: enums of string Literal, json field, ...)
Also, if you support this, are you going to support stubs in general?
What do you mean by that?
@vitalik sorry for the delay, I'll do the doc change today.
Question: is this common to type your fields instead of using django-stubs? Also, if you support this, are you going to support stubs in general?
not this has nothing to do with stubs - this let's you overrule default typing annotation when schema is automatically crated from model
@vitalik done
Hey @vitalik
Anything left to do on my side to get this merged?
Ping @vitalik