1

Say I have these models:

class MyModel(models.Model):
    pass

class OtherModel(models.Model):
    onetoone = OneToOneField(MyModel)

If obj here is of type MyModel, how can i then delete the onetoone such that I can use the hasattr-check later to find out that the onetoone does not exist any more? Is there some other way to find out that the onetoone has been deleted?

obj.onetoone.delete()
hasattr(obj, "onetoone")  # This still returns True, but actually it should return False
M.javid
  • 6,387
  • 3
  • 41
  • 56
totycro
  • 95
  • 1
  • 8
  • What is it you are trying to achieve here? are you trying to remove a relationship? – Sayse Aug 19 '15 at 09:56
  • Yes, I'd like to remove the relationship and delete the related object. Afterwards, I want the check to return False. – totycro Aug 19 '15 at 11:14

2 Answers2

2

Calling refresh_from_db of the related instance should do. You can make it transparent by overriding delete of the dependent model.

class OtherModel(models.Model):
    onetoone = OneToOneField(MyModel)

    def delete(self, using=None, keep_parents=False):
        result = self.delete(using, keep_parents)
        self.onetoone.refresh_from_db()
        return result
neuront
  • 9,312
  • 5
  • 42
  • 71
0

The hasattr will always return True, even if you've never created the relationship in the first place. It is not the right thing to be using here.

Instead, you need to check whether there is a related object.

try:
    obj.onetoone
except OtherModel.DoesNotExist:
    print("does not exist")
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • The first answer here however says that one can use `hasattr`: http://stackoverflow.com/questions/25944968/check-if-a-onetoone-relation-exists-in-django – totycro Aug 19 '15 at 11:16