retrieve model in function model

def iiicode():
lastid = MyModel.objects.filter(name=‘id’).last()
lastid_str = str(lastid)
mychar = ‘CODE’ + lastid_str
return mychar

class MyModel(models.Model):
nom = models.CharField(max_length=50)
prenom = models.CharField(‘Prénom’, max_length=100)
datenaiss = models.DateField(‘Date de naissance’, )
lieunaiss = models.CharField(‘Lieu de naissance’, max_length=100)
code = models.CharField(max_length=30, unique=True, default=iiicode())

def __str__(self):
    return self.code

Good evening dear all,

As indicated in the model file above, I try to execute a request inside a function to obtain the last id of a model that I concatenate with a character string. The value returned by the function is used to fill one of the fields of the same model. Only when I execute the code, I got an error message: “NameError: name = ‘MyModel’ is not defined”. I remind that I am in the file in which the class MyModel appears. I need help.


If your code is in the order you have here, your function iiicode is calling on MyModel before it’s defined. I would try to move the function after the model definition and see if that helps.


When I change the order in the code the error message concerns this time the iiicode function

“NameError: name ‘iiicode’ is not defined”

When are you expecting that function to be executed? If it’s in your file, it will only be called once, when the file is first loaded.

I think we would need to know what you’re trying to accomplish and under what circumstances you want it to be done.

If you’ve got this function in a view, we’d would probably need to see that view.

I just saw that iiicode gets called in the model, in the code field.

The problem that I’m seeing is that the original code had the iiifield function that relied upon MyModel that hadn’t been defined yet, while my suggestion means that the model relies on a function that hasn’t been defined yet.

I agree with Ken, we need to know what the code field is meant to do here.