Skip to content
Advertisement

Issue with class declaration in python. Two classes with fields of each other

My code is something like this:

class className1:
    fieldClassName2 = className2()

class className2:
    fieldClassName1 = className1()

and i have NameError: name ‘className2’ is not defined. I don’t know if there is a declaration in python like in c++, and you can call classes in any order. Please help me…

full code:

    class Speciality(models.Model):
    title = models.CharField(max_length=70)
    subject1 = models.ManyToManyField(Subject, verbose_name='Перший предмет', related_name='+')
    subject2 = models.ManyToManyField(Subject, verbose_name='Другий предмет', related_name='+')
    subject3 = models.ManyToManyField(Subject, verbose_name='Третій предмет', related_name='+')
    coefficient1 = models.FloatField()
    coefficient2 = models.FloatField()
    coefficient3 = models.FloatField()
    coefficient4 = models.FloatField()
    amount = models.IntegerField()
    budget_amount = models.IntegerField()
    department = models.ForeignKey(Department, verbose_name='Факультет', on_delete=models.CASCADE)
    code = models.IntegerField(default=0)
    abit = models.ManyToManyField(AdmissionList, verbose_name='Заявки', on_delete=models.CASCADE)

    def __str__(self):
        return str(self.code)

# there some another models

class AdmissionList(models.Model):
    user = models.ForeignKey(User, verbose_name='Абітурієнт', on_delete=models.CASCADE)
    speciality = models.ForeignKey(Speciality, verbose_name='Спеціальність', on_delete=models.CASCADE)
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE, null=True)
    firstRate = models.IntegerField(default=0)
    secondRate = models.IntegerField(default=0)
    thirdRate = models.IntegerField(default=0)
    avgRate = models.FloatField(default=0)
    summaryRate = models.FloatField(default=0)
    is_approved = models.BooleanField(default=False)

    def __str__(self):
        return self.user.full_name

field Speciality.abit is calls AdmissionList and field AdmissionList.speciality calls Speciality.

Advertisement

Answer

I think i avoid that problem by adding quotes into class call

abit = models.ManyToManyField(AdmissionList, verbose_name='Заявки', on_delete=models.CASCADE)
abit = models.ManyToManyField('AdmissionList', verbose_name='Заявки', on_delete=models.CASCADE)
Advertisement