Apologies if this isn’t the right section to post this.
I’m writing a tool to enhance the Django typing experience, and was trying to understand when a model field should be provided when using Manager/QuerySet.create
.
Consider the following model:
from django.db import models
class MyModel(models.Model):
name = models.CharField("name", max_length=255)
flag = models.BooleanField("flag")
Without the flag
field, MyModel.objects.create()
seems to work, as a default empty string value is provided for name
(and this without having null=True
or default=...
provided).
However, with the flag
field present, running the same empty create()
call leads to:
django.db.utils.IntegrityError: NOT NULL constraint failed: app_mymodel.flag
.
So my question is, how can I accurately infer a field as being required or not when using create
? I’ve tried using Field.get_default
, but it always falls back to an empty string (i.e. models.BooleanField("flag").get_default() == ""
).
I have the feeling that this cannot really be inferred accurately (as the exception thrown above happens at “the database level”, so Django seems to try to insert the row and catch any error that can happen, and does not perform any check beforehand). If that is the case, what signature would you expect when using create
? Should all fields be optional (i.e. provide = ...
in the signature), as we can’t know in advance if they are required or not?
Should some fields be set as required (i.e. do not provide = ...
in the signature) in some cases? Thinking about:
- a field that does not provide a
default
/db_default
(even if it works, as seen withCharField
) - a field that does not allow
null=True
(don’t know if this influences the fact that the field value doesn’t have to be provided).
Thanks!