Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
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, '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.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report

0

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)
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!