请帮助我解决我正在创建的名为
pharmcare
的 Django 应用程序,解决我遇到的问题。我已经被这个值错误困住了两天了,我研究了如何在使用 ManyToMany
关系时解决它,包括阅读 Django 文档。尽管如此,我最终还是没有得到患者的总付款http://127.0.0.1:8000/pharmcare/patient-list/
,这在我的第二个解决方案中有点奇怪,我相信我在第二个解决方案中遗漏了一些东西。拜托,我确实希望在药剂师添加折扣价格后动态保存总数,如果没有我设置为 null and blank=True
的折扣,我希望之前的总数也保存在我的 PostgreSQL 的pharmaceutical_care_plan 表中.
这是我的模型:
class PharmaceuticalCarePlan(models.Model):
class Meta:
ordering = ['id']
user = models.ForeignKey('songs.User', on_delete=models.CASCADE)
pharmacist = models.ForeignKey(
"Pharmacist", on_delete=models.SET_NULL, null=True, blank=True)
organization = models.ForeignKey(
'leads.UserProfile', on_delete=models.CASCADE)
patients = models.ManyToManyField('Patient')
patient_unique_code = models.CharField(
max_length=20, null=True, blank=True)
total_payment = models.PositiveBigIntegerField(null=True, blank=True)
discount = models\
.PositiveBigIntegerField(null=True, blank=True,
help_text="discount given to patient,\
perhaps due to his/her consistent loyalty strictly authorized by \
management (if any).")
# other codes
slug = models.SlugField(null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self) -> str:
if self.monitoring_plan:
return f'The {self.monitoring_plan.frequency}'
return "Frequency of monitoring plan was not provided, perhaps\
you forgot to select the field in the form."
def get_pharmcare_absolute_url(self):
reverse("pharmcare:patients-detail",
kwargs={"pk": self.pk})
# error is coming from here
def get_total(self) -> int:
""" get's the total amount paid throughout the pharmcare cycle of the
patient."""
total = 0
# where the error is coming from according to django error-traceback (line
# 124 of my model)
for patient_list in self.patients.all():
total += patient_list.get_total_charge()
# check discount if any
if self.discount is None:
return patient_list.get_total_charge()
total -= self.discount
return total
def get_total_when_no_discount(self) -> int:
""" patient_pharmcare_summary = PharmaceuticalCarePlan.objects.filter(
id=self.pk) """
# pt_name = Patient.objects.get(id=self.pk)
total = 0
# for patient_list in patient_pharmcare_summary:
for patient_list in self.patients.all():
total = patient_list.get_total_charge()
return total
# wrote some bunch of other codes here not useful to this question
# Here is what I tried as my 2nd solution in the model for id to be assigned to the
# `ManyToMany relationship column: patients`. However, the Value-error disappeared
# but it returns None as a value from db. :-(
def get_total(self) -> int:
""" get's the total amount paid throughout the pharmcare
cycle of the patient."""
# pt_name, created = Patient.objects.get_or_create(id=self.pk)
patient_pharmcare_summary = PharmaceuticalCarePlan.objects.filter(id=self.pk)
#
total = 0
for patient_lists in patient_pharmcare_summary:
for patient_list in patient_lists.patients.all():
patient_ = patient_list
total += patient_.get_total_charge()
if self.discount:
total -= self.discount
return total
return patient_list.get_total_charge()
这是我的观点:
class PatientSummaryCreateView(OrganizerPharmacistLoginRequiredMixin, CreateView):
""" Handles request-response cycle made by the admin/pharmacists
to create a patient"""
template_name = 'pharmcare/pharmaceutical_care_plans/patients-create.html'
form_class = PharmaceuticalCarePlanModelForm
def get_queryset(self, slug, *args, **kwargs):
user = self.request.user
patients = get_object_or_404(Patient, slug=slug)
if user.is_organizer:
self.queryset = PharmaceuticalCarePlan.objects.filter(
organization=user.userprofile)
else:
self.queryset = PharmaceuticalCarePlan.objects.filter(
organization=user.pharmacist.organization)
self.queryset = self.queryset.filter(
pharmacist__user=self.request.user)
return self.queryset
def form_valid(self, form: BaseModelForm) -> HttpResponse:
user = self.request.user
form = form.save(commit=False)
form.user = user
form.organization = user.userprofile
form.patient_unique_code = generate_patient_unique_code()
form.slug = slug_modifier()
form.total_payment = form.get_total()
form.save()
if reminder_time(): # show this from 11hr to 12hr everyday
messages.warning(self.request,
f"""Please Pharm {user.username.title()},
be cautious of given
discount to customers! Any discount must be authorized by the
management.""")
return super(PatientSummaryCreateView, self).form_valid(form)
def get_success_url(self) -> str:
return reverse('pharmcare:patients')
```py
Here is my Form:
```py
class PharmaceuticalCarePlanModelForm(forms.ModelForm):
""" Pharmceutical care form that handles user input and validations """
class Meta:
model = PharmaceuticalCarePlan
fields = [
'patients',
'has_improved',
'progress_note',
'medication_changes',
'analysis_of_clinical_problem',
'monitoring_plan',
'follow_up_plan',
'discount'
]
这是我的模板:患者.html:
<tbody>
{% for patient_qs in patient_list %}
<tr
class="bg-white border-b dark:bg-gray-800 dark:border-gray-700
hover:bg-gray-50 dark:hover:bg-gray-600"
>
<td class="w-4 p-4">
<div class="flex items-center">
<span>{{forloop.counter }}</span>
</div>
</td>
{% for pt in patient_qs.patients.all %}
<td class="px-6 py-4">{{ pt.get_full_name }}</td>
{% endfor %}
{% comment %} deleted some bunch of codes here which are not
useful based on the question {% endcomment %}
{% if patient_qs.discount > 1 %}
<td class="px-6 py-4">₦{{ patient_qs.total }}</td>
{% else %}
<td class="px-6 py-4">₦{{patient_qs.get_total_when_no_discount }}</td>
{%endif %}
<td class="px-6 py-4"> {{ patient_qs.date_created }} in UTC </td>
<td class="flex items-center px-6 py-4">
<a
href="
{% url "pharmcare:patients-detail" patient_qs.pk %}
"
class="pr-2 font-medium text-blue-600 dark:text-blue-500 hover:underline"
>For Further Details</a
>
</td>
</tr>
</tbody>
{% endfor %}
谢谢你。
class PatientSummaryCreateView(OrganizerPharmacistLoginRequiredMixin, CreateView):
""" Handles request-response cycle made by the admin/pharmacists
to create a patient"""
template_name = 'pharmcare/pharmaceutical_care_plans/patients-create.html'
queryset = PharmaceuticalCarePlan.object.all()
form_class = PharmaceuticalCarePlanModelForm
添加 queryset = PharmaceuticalCarePlan.object.all() 到视图