#35731: Extend documentation about db_default and DatabaseDefault
-------------------------------------+-------------------------------------
Reporter: Kyle Bebak | Owner:
Type: | YashRaj1506
Cleanup/optimization | Status: assigned
Component: Database layer | Version: dev
(models, ORM) |
Severity: Normal | Resolution:
Keywords: | Triage Stage: Accepted
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by Kyle Bebak):
Indeed, the way I solved this problem was setting both `default` and
`db_default`. I'm guessing this is a fairly common use case, especially
for `BooleanField`, `IntegerField`, `CharField`/`TextField`, etc, where
you usually don't need a DB `Func` or Python function to set a default
value for the field. E.g. I use Django as the SOT for the DB schema, but I
don't only write to the DB with the Django ORM, so having both `default`
and `db_default` is useful for me.
Also, I understand that the model instance needs a sentinel value so it
knows to set `foo.val` after `foo` has been written to the DB. My proposal
is that the sentinel value not be stored on `foo.val`, but rather in some
"private" attribute not likely to be touched by client code. Before `foo`
is written to the DB, I think `foo.val` should be `None`, not an instance
of `DatabaseDefault` (which can be stored elsewhere on the model
instance).
This probably seems like splitting hairs, and not a good reason for
changing the implementation. I like the sentinel living elsewhere because
it makes the model's type interface simpler.
If `default` is passed to the field, then `val` has a type of `int`. If
it's not, then its type is `int | None`. In my proposal above, passing
`db_default` wouldn't change the type of `foo`, whereas the current
implementation means its type is `int | DatabaseDefault`, `int | None`, or
`int`, depending on what combo of `default` and `db_default` is passed.
Anyway, I think a change in documentation would be a good outcome for this
ticket, and that there should be an example of passing both `default` and
`db_default` in the docs. Thank you for taking the time to look at this =)
--
Ticket URL: <https://code.djangoproject.com/ticket/35731#comment:4>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/01070191c318dc0a-db491f1e-d7b4-4dd0-9d37-15d4255ae2b9-000000%40eu-central-1.amazonses.com.