我在models.py中定义了2个类:
class Job(models.Model):
job_id = models.CharField(primary_key=True, max_length=10)
job_title = models.CharField(max_length=35)
min_salary = models.IntegerField(blank=True, null=True)
max_salary = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'jobs'
def __str__(self):
return self.job_id
class Employee(models.Model):
employee_id = models.IntegerField(primary_key=True)
first_name = models.CharField(max_length=20, blank=True)
last_name = models.CharField(max_length=25)
email = models.CharField(unique=True, max_length=25)
phone_number = models.CharField(max_length=20, blank=True)
hire_date = models.DateField()
job = models.ForeignKey('Job')
salary = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
commission_pct = models.DecimalField(max_digits=2, decimal_places=2, blank=True, null=True)
manager = models.ForeignKey('self', blank=True, null=True, related_name ='employee')
department_id = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'employees'
def __str__(self):
return self.employee_id
def __unicode__(self):
return self.employee_id
问题在于外键,在Employees管理页面上,Job字段正确显示包含所有可能的job_id的下拉列表,但是manager字段显示下拉列表,所有条目都等于“Employee object”。我怀疑这是因为经理是self.employee
的外键。
我该如何解决?
谢谢。
答案 0 :(得分:1)
您在__str__
课程中定义了__unicode__
和Employee.Meta
方法。
将它们缩进四个空格,你应该是好的:
class Employee(models.Model):
employee_id = models.IntegerField(primary_key=True)
first_name = models.CharField(max_length=20, blank=True)
last_name = models.CharField(max_length=25)
email = models.CharField(unique=True, max_length=25)
phone_number = models.CharField(max_length=20, blank=True)
hire_date = models.DateField()
job = models.ForeignKey('Job')
salary = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
commission_pct = models.DecimalField(max_digits=2, decimal_places=2, blank=True, null=True)
manager = models.ForeignKey('self', blank=True, null=True, related_name ='employee')
department_id = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'employees'
def __str__(self):
return self.employee_id
def __unicode__(self):
return self.employee_id
答案 1 :(得分:0)
在__unicode__()
模型中添加__str__()
或Employee
方法,就像在Job
中一样。
class Employee(models.Model):
def __unicode__(self):
return self.email #or whatever string you want
此方法用于在django中将对象表示为字符串。