我完成的代码仅显示数据库中的一个第一保存记录
id数据是否包含多个。
class Lab(models.Model):
address=models.CharField(max_length=150)
age=models.IntegerField(blank=True,default=11)
sex_category=(('Male','Male'),('Female','Female'),('Others','Others'),)
sex=models.CharField(max_length=50,choices=sex_category,default="Male")
contact=models.CharField(max_length=20)
image=models.ImageField(upload_to = 'photo/',blank=True,null=True)
user = models.OneToOneField(UserProfile)
# patient=models.ForeignKey(Patient)
def has_perm(self,perm,obj=None):
return self.is_lab
def has_module_perms(self,app_Label):
return self.is_lab
def __str__(self):
return self.user.name
class Lab_Test(models.Model):
test_name=models.CharField(max_length=250,blank=False)
status=models.CharField(max_length=250,blank=False,choices=(('Done','Done'),('Pending','Pending')),
default='Pending')
result=models.TextField(max_length=250,blank=True)
test_date=models.DateTimeField(default=datetime.now)
patient=models.ForeignKey(Patient)
lab=models.ForeignKey(Lab)
def __str__(self):
return self.patient.name
@login_required(login_url='/login/')
def lab_check_pats_list(request):
if request.user.is_lab:
lab=UserProfile.objects.get(id=request.user.id)
labs=Lab.objects.get(user=lab.id)
labt=Lab_Test.objects.filter(lab_id=labs.id)
print(labt)
pt = []
for x in labt:
pt.append(x.patient_id)
pts= Patient.objects.filter(id__in=pt)
context={
'ab':zip(pts,labt)
}
print(pts)
return render(request,'lab_check_pats_list.html',context)
我想获取过滤器ID的所有记录,但仅显示 一次id 1,2,3,4 data contains more than one but it is showing only once
答案 0 :(得分:0)
您的问题在这里:
context={
'ab':zip(pts,labt)
}
压缩结果时,它首先映射Lab
到第一个Patient
,这就是为什么看到一个结果的原因。我建议您采取更像Django的方法。像这样:
首先像这样更新实验室测试:
class Lab_Test(models.Model):
test_name=models.CharField(max_length=250,blank=False)
status=models.CharField(max_length=250,blank=False,choices=(('Done','Done'),('Pending','Pending')),
default='Pending')
result=models.TextField(max_length=250,blank=True)
test_date=models.DateTimeField(default=datetime.now)
patient=models.ForeignKey(Patient, related_name="labtests") # Updated here
lab=models.ForeignKey(Lab)
然后按如下所示更改视图:
@login_required(login_url='/login/')
def lab_check_pats_list(request):
if request.user.is_lab:
lab=UserProfile.objects.get(id=request.user.id).lab # Because its a OneToOne relation
lab_tests=Lab_Test.objects.filter(lab=lab)
context={
'lab_tests': lab_tests
}
return render(request,'lab_check_pats_list.html',context)
现在在模板中,您可以像这样访问患者值:
{% for lab_test in lab_tests %}
{{ lab_test.patient.name }}
{{ lab_test.patient.contact }}
{{ lab_test.id }}
{% endfor %}