Opened 2 years ago

Closed 2 years ago

#28512 closed Uncategorized (invalid)

save() behavior of a parent model class accessed through _ptr attribute

Reported by: wckao Owned by: nobody
Component: Uncategorized Version: 1.11
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

Not sure if this is really a bug, but the behavior is not what I expected.
With model

from django.db import models

class RelatedModel(models.Model):
    name = models.CharField(max_length=20)

class ModelA(models.Model):
    related = models.ForeignKey(RelatedModel)

    def set_related(self):
        self.related = RelatedModel.objects.get(name="related_model2")
        self.save()


class ModelB(ModelA):
    name = models.CharField(max_length=20)

    def set_related(self):
        self.modela_ptr.set_related()

When running the following script

r1 = RelatedModel.objects.create(name="related_model1")
r2 = RelatedModel.objects.create(name="related_model2")

b1 = ModelB.objects.create(related=r1, name="b1")   # b1.related.name == "related_model1"
b1.set_related()                      # b1.related.name should be "related_model2" now
print(b1.related.name)          # shows "related_model1"

Change History (2)

comment:1 Changed 2 years ago by wckao

It works if I calls b1.refresh_from_db() before accessing b1.related.name.

comment:2 Changed 2 years ago by wckao

Resolution: invalid
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top