#35027 closed Bug (duplicate)

Error Creating a Model with a GeneratedField

Reported by: Jason Christa Owned by: nobody
Component: Database layer (models, ORM) Version: 5.0
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

class ProjectHealth(models.Model):
    class HEALTH(models.TextChoices):
        GREEN = "green", "Green"
        YELLOW = "yellow", "Yellow"
        RED = "red", "Red"
        NA = "not applicable", "N/A"


    project = models.ForeignKey("Project", on_delete=models.CASCADE)
    health = models.CharField(
        choices=HEALTH.choices, max_length=50, default=HEALTH.GREEN, db_default=HEALTH.GREEN
    )
    health_value = models.GeneratedField(
        expression=Case(
            When(health=HEALTH.GREEN, then=Value(1)),
            When(health=HEALTH.YELLOW, then=Value(2)),
            When(health=HEALTH.RED, then=Value(3)),
            default=Value(0),
        ),
        output_field=models.IntegerField(),
        db_persist=True,
    )

In this simple model when I try to create a new ProjectHealth record, health_value is set as a deferred field in base save(). This causes the rest of the save process to treat this as an update instead of an insert. It ends with the error Cannot force an update in save() with no primary key.

Change History (1)

comment:1 by Simon Charette, 13 months ago

Resolution: duplicate
Status: newclosed

Duplicate of #35019, will be fixed in Django 5.0.1 expected to be released on Jan 2nd.

Note: See TracTickets for help on using tickets.
Back to Top