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, 'Executive'),
(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.
From the Django docs: http://docs.djangoproject.com/en/dev/ref/models/fields/#choices
Finally, note that choices can be any iterable object — not necessarily a list or tuple. This lets you construct choices dynamically. But if you find yourself hacking choices to be dynamic, you're probably better off using a proper database table with a ForeignKey. choices is meant for static data that doesn't change much, if ever.
If you are using django admin, You can do it.
class EmployeeAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
form = super(EmployeeAdmin, self).get_form(request, obj, **kwargs)
form.base_fields['manager'].queryset = Employee.objects.filter(is_manager=True)
return form
Then in models
manager = models.ForeignKey('self', on_delete=models.PROTECT, null=True, blank=True)
In admin.py
admin.site.register(Employee, EmployeeAdmin)