#36472: GeneratedField(primary_key=True) crashes on create(), and other issues
-------------------------------------+-------------------------------------
     Reporter:  David Sanders        |                    Owner:  (none)
         Type:  Uncategorized        |                   Status:  new
    Component:  Database layer       |                  Version:  dev
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:
     Keywords:                       |             Triage Stage:
                                     |  Unreviewed
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------
Changes (by Simon Charette):

 * cc: Simon Charette (added)

Comment:

 I haven't played with it a lot so take this with a grain of salt but I
 think the crux of the issue here is that we mark generated field as
 deferred on instance that are meant for ''adding''.

 We don't do that for any other fields even the one that are db generated
 (think of `Field.db_default` usage) and it makes little sense knowing
 there's nothing to fetch until persistence is performed.

 If we're speaking code here I meant that for a model of the form

 {{{#!python
 from django.db import models

 class Foo(models.Model):
     field = models.IntegerField()
     field_db_default = models.IntegerField(
         db_default=models.Value(1)
     )
     field_generated = models.GeneratedField(
         expression=models.F("field"),
         db_persist=True,
         output_field=models.IntegerField()
     )

 def run():
     instance = Foo()
     print(repr(instance.field))
     print(repr(instance.field_db_default))
     try:
         print(repr(instance.field_generated))
     except Exception as exc:
         print(f"Failed to access instance.field_generated: {exc}")
 }}}

 [https://dryorm.xterm.info/ticket-36472 You'd get] the following output

 {{{
 None
 <django.db.models.expressions.DatabaseDefault object at 0x7f9ba68a27b0>
 Failed to access instance.field_generated: Cannot read a generated field
 from an unsaved model.
 }}}


 As David pointed out on the forum this has a bit of overlap with #27222.
-- 
Ticket URL: <https://code.djangoproject.com/ticket/36472#comment:2>
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 visit 
https://groups.google.com/d/msgid/django-updates/0107019783c1a254-a4af87e1-9972-4d30-8c97-6d47194c3dc4-000000%40eu-central-1.amazonses.com.

Reply via email to