Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

188
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda