Brainstorm's snippets (1/247)

  Check reverse relation for OneToOneField

If related object does not exist, any direct reference to it produces the exception:

RelatedObjectDoesNotExist: Contatore has no pratica.

To avoid it, explicitly test the existence of the attribute:

class Contatore(BaseModel):

    ...

    def is_istallato(self):
        return hasattr(self, 'pratica') and self.pratica is not None

where:

class Pratica(BaseModel):

    ...

    contatore = models.OneToOneField(Contatore, null=True, blank=True, on_delete=models.SET_NULL)

References: