def staff_detail(request, nid): """ 员工个人详情页面 """ staff_info = models.StaffInfo.objects.filter(RES_ID=nid).first() emergency_info = models.Emergency.objects.filter(res_id=nid).first() print(emergency_info) print(staff_info) StaffForm = StaffStaticModelForm(instance=staff_info) EmergencyForm = EmergencyStaticModelForm(instance=emergency_info) return render(request, "staff_detail.html", {"StaffForm": StaffForm, "EmergencyForm": EmergencyForm})这段代码目前能显示一条与StaffInfo关联的Emergency数据,如何得到所有关联的Emergency?
时间: 2024-03-14 20:47:21 浏览: 267
可以使用`ForeignKey`的`related_name`属性来获取所有关联的Emergency数据。在`StaffInfo`模型中,可以将`Emergency`模型的外键设置为`staff_info`,并给它设置一个`related_name`属性。然后在查询`StaffInfo`对象时,可以通过该属性来获取所有关联的`Emergency`对象。
具体实现代码如下:
```python
class StaffInfo(models.Model):
# ...
class Emergency(models.Model):
staff_info = models.ForeignKey(StaffInfo, related_name='emergency_list', on_delete=models.CASCADE)
# ...
def staff_detail(request, nid):
staff_info = models.StaffInfo.objects.filter(RES_ID=nid).first()
emergency_list = staff_info.emergency_list.all()
StaffForm = StaffStaticModelForm(instance=staff_info)
EmergencyFormset = modelformset_factory(Emergency, form=EmergencyStaticModelForm, extra=0)
EmergencyFormset = EmergencyFormset(queryset=emergency_list)
return render(request, "staff_detail.html", {"StaffForm": StaffForm, "EmergencyFormset": EmergencyFormset})
```
在`Emergency`模型中,设置`staff_info`为`StaffInfo`模型的外键,并设置`related_name`为`emergency_list`。在`staff_detail`视图函数中,使用`emergency_list`变量来获取所有关联的`Emergency`对象,并将其传递给`EmergencyFormset`。然后在模板中使用`{{ EmergencyFormset }}`来渲染所有的`Emergency`表单。
阅读全文