lundi 17 avril 2017

Django: self referential foreign key with choice list

My model defines an employee, which has a name, ID, job, and manager. I'd like to be able to specify a list of choices of Employees that could be listed as another employees manager (similar to the jobs field). To do so I have included

class Employee(models.Model):
    EXECUTIVE = 'EXC'
    SALESMAN = 'SAL'
    ENGINEER = 'ENG'
    CLERK = 'CLK'
    JOBS = (
        (EXECUTIVE, 'Assistant Engineer'),
        (SALESMAN, 'Salesman'),
        (ENGINEER 'Engineer'),
        (CLERK, 'Clerk'),
    )
    employee_id = models.CharField(max_length = 5, primary_key=True)
    name = models.CharField(max_length=25)
    job = models.CharField(max_length=3, choices=JOBS) 
    is_manager = models.BooleanField(default=False)
    manager = models.ForeignKey('self', on_delete=models.PROTECT, null=True, choices=get_managers()) 

    def __str__(self):
        return self.name

Also in my models.py I have defined the following function:

def get_managers():
    managers = []
    for manager in Employee.objects.filter(is_manager=True):
        managers.append((manager.employee_id, manager.name))
    return managers

My problem is that when the function is placed before the Employee class definition I get NameError: name 'Employees' is not defined and when placed after the Employee class definition the error NameError: name 'get_managers()' is not defined. I have tried placing the get_managers() within the class and get `NameError: name 'get_managers()' is not defined

If there are better ways of accomplishing the same thing I would be open to suggestions.






Comments
0 Comments

0 commentaires:

Enregistrer un commentaire