我想将模型与那里的 id 链接起来,我在获取与 id 链接的外键对象并创建查询集时遇到了麻烦,我是 Django 的新手,我已经搜索了很多关于我的问题但没有得到答案。
模型.py:
class Patient(models.Model):
name = models.CharField(max_length=200);
phone = models.CharField(max_length=20);
address = models.TextField();
Patient_id = models.AutoField(primary_key=True);
Gender= models.CharField(choices=GENDER,max_length=10)
consultant = models.CharField(choices=CONSULTANT,max_length=20)
def __str__(self):
return self.name
class Ipd(models.Model):
reason_admission = models.CharField(max_length=200, blank=False)
presenting_complaints = models.CharField(max_length=200,)
ipd_id = models.AutoField(primary_key=True)
rooms = models.ForeignKey(Rooms,on_delete=models.CASCADE,
blank=False)
date_of_admission = models.DateField(("Date"),
default=datetime.date.today)
patient =
models.ForeignKey(Patient,on_delete=models.CASCADE,blank=False)
def __str__(self):
return self.patient.name
形式.py:
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = ['name', 'phone', 'address', 'Patient_id', 'consultant',
'Gender']
class IpdForm(ModelForm):
class Meta:
model = Ipd
fields = ['patient','reason_admission','presenting_complaints',
'rooms','date_of_admission']
视图.py:
@login_required
def ipd (request,patient_id):
p = Patient.objects.get(pk=patient_id)
if request.method=="POST":
formtwo = IpdForm(request.POST,instance=p)
if formtwo.is_valid() :
formtwo.user_id = request.user.id
if formtwo.save():
return HttpResponseRedirect('ipd_list.html',
messages.success(request, 'Patient is successfully updated.', 'alert-
success'))
else:
return render('ipd_list.html', messages.error(request,
'Data is not saved', 'alert-danger'))
else:
return HttpResponse(formtwo.errors)
else:
formtwo = IpdForm()
return render(request, 'newipd.html', {'p':p ,'form2':formtwo})
html :
<div class="card-panel">
<span class="blue-text text-darken-2">Name : {{p.name}}</span> <br> <span
class="blue-text text-darken-2">Phone : {{ p.phone }}</span><br>
</div>
我在使用 queryset 时遇到问题,它允许我将一个模型的对象用于另一个
您的问题不是很清楚,但是如果您想根据患者 ID 获取 Ipd 查询集,您可以这样做:
qs = Ipd.objects.get(patient=patient_id)
如果您想要患者的 Ipd 列表,您可以执行以下操作:
qs = Patient.idp_set.all()
在为患者获取所有 Ipd 的 html 模板中,您将使用
{{ object.ipd_set.all }} .
您需要将患者作为对象传递。
如果你想循环这个,你需要使用:
{% for ipd in object.ipd_set.all %}
do stuff
{% endfor %}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句