我正试图访问oneToOne关系,但对我没有用。
根据此文档 https://docs.djangoproject.com/en/2.0/topics/db/examples/one_to_one/
A Restaurant can access its place:
>>> r.place
<Place: Demon Dogs the place>
A Place can access its restaurant, if available:
>>> p1.restaurant
<Restaurant: Demon Dogs the restaurant>
这是我的model.py
class Employee(models.Model):
idemp = models.CharField(max_length=100)
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class EmployeeDetail(models.Model):
nationality = models.CharField(max_length=50)
employee = models.OneToOneField(Employee,on_delete=models.CASCADE,primary_key=True,)
这是我的view.py
class EmployeeListView(ListView):
context_object_name = 'employees'
model = models.Employee
和我的employee_list.html
{% for employee in employees %}
<tr>
<td>{{ employee.idemp }}</td>
<td>{{ employee.name }}</td>
<td>{{ employee.nationality }}</td>
</tr>
{% endfor %}
运行它,结果只显示idemp
和name
。
我错过了什么吗?...
也
我将employee
和employe details
表分成2个表,因为我已经访问了数据,并且只显示了4个列的员工列表,其他(详细信息)将访问所有列。
哪个更好?...
1. use one table for many columns
或
2. split the table into 2 or more for many columns
(就像我的情况一样,我将employee
和employeedetails
分开了
请与why
和because
解释,我的大脑有点慢。
非常感谢
答案 0 :(得分:1)
您可以访问带有OneToOne
属性的反向modelname
字段,employeedetail
。要获得nationality
,您需要执行employee.employeedetail.nationality
。试试这个:
{% for employee in employees %}
<tr>
<td>{{ employee.idemp }}</td>
<td>{{ employee.name }}</td>
<td>{{ employee.employeedetail.nationality }}</td>
</tr>
{% endfor %}