Pregunta

I have the following models

class Entry(models.Model):
    #fields....


class EntryHistory(models.Model):
     entry = models.OneToOneField(Entry, related_name='history')
     text =.....etc

But when i try to access entry.history I get a DoesNotExist exception

code in shell

entry = Entry.objects.get(pk = 4)
entry_history = entry.history
    raise self.related.model.DoesNotExist
DoesNotExist

I want to check if an entry_history has been added for the specific entry. So i want to get the entry.history and check

if entry_history:

to see if there was an entry_history or not. What does the DoesNotExist mean?

 hasattr(entry, 'history')

returns false also.

EDIT: SQL table creation code

CREATE TABLE "mycal_entryhistory" ("id" integer NOT NULL PRIMARY KEY, "entry_id" integer NOT NULL UNIQUE, "text" text NULL, "doctor_id" integer NOT NULL)

Does that mean that my table wasn't created properly?

¿Fue útil?

Solución

You want to check if an entry_history has been added for the specific entry and related.model.DoesNotExist means that it does not exists, so the exception is an answer to your question.

entry = Entry.objects.get(pk=4)
try:
    entry_history = entry.history
    # if this code runs it means the object exists
except entry.history.model.DoesNotExist:
    # it does not exist

Alternatively you can use count:

entry = Entry.objects.get(pk=4)
if entry.history.count():
    # it does exist
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top