#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 Simon Charette):

 > I think foo.val should be None, not an instance of DatabaseDefault
 (which can be stored elsewhere on the model instance).

 Without getting into all the details there are complications in doing that
 as `None` is already used to denote `NULL` and a field with a `db_default`
 could also be marked `null=True` and assigned `None` before creation to
 take precedence over `db_default`

 {{{#!python
 class Author(models.Model):
     favorite_color = models.CharField(db_default="green", null=True)

 author = Author()
 assert isinstance(author, DatabaseDefault)
 author.favorite_color = None
 author.save()
 author.refresh_from_db()
 assert author.favorite_color is None
 }}}


 In other words we can't use `None` as a sentinel denote a fallback to
 `db_default` as it might be explicitly assigned as a desired value.

 > 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.

 That's a bad assumption unfortunately, every property associated with a
 field are `| Expression[F]` where `F` is bound to the field type and
 represents its `output_field`. In other words, `IntegerField(null=True)`
 results in a descriptor that is `int | None | Expression[IntegerField]`
 and not simply `int | None`.
-- 
Ticket URL: <https://code.djangoproject.com/ticket/35731#comment:5>
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/01070191c3ac32b7-bc071217-b37e-4631-a24f-d4280918fbab-000000%40eu-central-1.amazonses.com.

Reply via email to