0

I have these model for example (now noses have names):

class Person(models.Model):
    id = models.AutoField(primary_key=True)

class Nose(models.Model):
    id = models.AutoField(primary_key=True)
    owner = models.OneToOneField('Person', on_delete=models.CASCADE, primary_key=False, related_name='nose')
    name = models.CharField(max_length=50, null=True, blank=True)

And I have this code that deletes a person nose (horrible accident...):

danny = Person()
danny.save()

# danny.nose would raise: {RelatedObjectDoesNotExist}Person has no nose.

nose = Nose(owner=danny, name='Big one')
nose.save()

# Now data in 'danny' is: 
# "id" attribute: 1
# "nose" attribute: nose instance with name "Big one" and id 1
# danny.nose would return the nose instance

if hasattr(danny, 'nose'):
    danny.nose.delete()

# After delete: data in 'danny': 
# id = 1
# nose: nose instance with name "Big one" and id None
# danny.nose would return the nose instance with None id

danny_from_db = Person.objects.filter(id=1).first()
# data in danny_from_db: id = 1, no "nose" attribute - hasattr(danny, 'nose') would return False
# danny_from_db.nose would raise: {RelatedObjectDoesNotExist}Person has no nose.

Why does the Person instance keeps that Nose attribute with None id, after deleting it from DB?

Shahaf Shavit
  • 184
  • 1
  • 1
  • 8
  • https://stackoverflow.com/a/12754229/541277 – themanatuf Jan 23 '20 at 12:22
  • @themanatuf Different issue. – Shahaf Shavit Jan 23 '20 at 13:07
  • 1
    `danny_from_db = Person.filter(id=1).first()` is wrong. Would be: `danny_from_db = Person.objects.filter(id=1).first()` And for delete issue: Look you are actually deleting the nose entity related with the person instance. not the Person instance. SO it says: appname.models.Person.nose.RelatedObjectDoesNotExist: Person has no nose. – Iqbal Hussain Jan 23 '20 at 15:34
  • @IqbalHussain sorry it's my mistake. It's `Person.objects.filter(id=1).first()`. That is not the problem that I have in my code. – Shahaf Shavit Jan 29 '20 at 14:58

0 Answers0