Django Model not defined


I’ve been working on some views and using a model for like a week now and there was no issues until now: I did not change anything but add a new field to the model, and now myModel.objects.create() gives me a name is not defined error. I have the model imported and as I said, I’ve been working on this for a week and I created several models using the exact same code.


class Prescription(models.Model):
    prescription_id = models.CharField(max_length=26, default=prescription_id, editable=False, unique=True) # THIS IS THE FIELD I ADDED BEFORE HAVING THIS ERROR
    appointment = models.ForeignKey('booking.Appointment', on_delete=models.SET_NULL, null=True, blank=True)
    doctor = models.ForeignKey('core.Doctor', on_delete=models.CASCADE)
    patient = models.ForeignKey('core.Patient', on_delete=models.CASCADE)
    overriden_date = models.DateField(null=True, blank=True)
    control = models.BooleanField(default=False)
    control_date = models.DateField(null=True, blank=True)
    send_email = models.BooleanField(default=False)
    posted = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "Ordonnance"
        verbose_name_plural = "Ordonnances"

    def __str__(self):
        return str(

class PrescriptionElement(models.Model):
    prescription = models.ForeignKey('Prescription', on_delete=models.CASCADE)
    drug = models.ForeignKey(Drug, on_delete=models.CASCADE, null=True)
    custom = models.CharField("Elément", max_length=25, null=True, blank=True)
    dosage = models.CharField(max_length=45, null=True, blank=True)
    posologie = models.CharField(max_length=256, null=True, blank=True)
    duration = models.CharField("Durée", max_length=15, null=True, blank=True)


PrescriptionElement.objects.create(prescription=prescription, drug=listemedicament, custom=medicament, dosage=dosage, posologie=posologie, duration=duree)


name 'PrescriptionElement' is not defined


I fixed the issue by removing any circular relation between multiple files. Circular Imports are the one problem causing this. The prescription_id default value was defined in a file called, and in there are some functions inheritting models from the file. Removing this circular relationship fixes this issue.

Also, using this format to defined ForeignKeys (‘booking.Appointment’) is the better choice to avoir importing.

Answered By – Kaiss B.

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published