Django 表单 - Select 下拉菜单

Django Form - Select dropdown

How do I Output both "id_no" and "name" [id_no - name] combined in dropdown select form. Can it be done directly to the form using {{form}} only.

Model:
class Employee(models.Model):
  id_no = models.CharField(unique = True,max_length=6)
  name = models.CharField(max_length=100)

Form:
class EmployeeForm(forms.ModelForm):
  class Meta:
   model = Employee
   fields = __all__
    
    
    

是的,使用 {{form}} 实现 str :

直接在表单中完成
class Employee(models.Model):
    id_no = models.CharField(unique = True,max_length=6)
    name = models.CharField(max_length=100)

    def __str__(self):
        return f"{self.id_no} - {self.name}"

但在 EmployeeForm 上不行,因为此表单没有用于选择员工的下拉菜单。您将在 modelFrom 上看到它,用于带有员工外键的表单。