`UNIQUE 约束失败于:我的 pharmcare 应用程序中的 pharmcare_patent.id`

问题描述 投票:0回答:1

我目前正在开发的项目中有一个名为 pharmcare 的 Django 应用程序,每当我想重写

save()
方法来插入/保存患者支付的
total
付款时,我就会遇到一个独特的约束问题这样创建表格或更新患者记录的药剂师就不会手动执行数学运算。每当我在 view.py 上使用
CreateView
中的表单而不用我动态创建的函数覆盖 save 方法来解决数学问题时,它都会很好地完成工作,但在管理面板中,答案不会出现在那里。但是,如果我尝试在应用程序的
save()
中使用
models.py
,我会收到该错误。如果我删除模型中的 save() 方法,错误就会消失,这不是我想要的,因为我希望药剂师完成创建或修改表单后立即将其保存在数据库中。我已经使用
get_or_create
方法来解决它,但它仍然流产,并且我不想使用另一个选项(因为我希望网站所有者可以选择删除轻松创建记录的药剂师/组织者)与她/他创建的记录一起)是外键
SET_NULL
函数的
on_delete
。我使用的数据库是 PostgreSQL 顺便说一句。

这是我的病人表的药物护理模型:


class Patient(models.Model):
   
    medical_charge = models.PositiveBigIntegerField(blank=True, null=True,
                             verbose_name="amount paid (medical charge if any)")
    notes = models.TextField(null=True, blank=True)

    pharmacist = models.ForeignKey(
        "Pharmacist", on_delete=models.SET_NULL, null=True, blank=True)
    organization = models.ForeignKey(
        'leads.UserProfile', on_delete=models.CASCADE)

    user = models.ForeignKey(
        'songs.User', on_delete=models.CASCADE)
    patient = models.ForeignKey(
        'PatientDetail', on_delete=models.CASCADE,
        verbose_name='Patient-detail')

    medical_history = models.ForeignKey(
        'MedicationHistory',
        on_delete=models.CASCADE)

    total = models.PositiveBigIntegerField(editable=True, blank=True,
                                   null=True, verbose_name="Total (auto-add)")

    slug = models.SlugField(null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['id', '-date_created']

    def __str__(self):
        return self.patient.first_name

    def get_total_charge(self) -> int:
        total = 0
        # check whether there is additional charges like drug price to be added
        # if yes, then add medical charges to the total
        if self.medical_charge:
            amount_charged = self.patient.consultation + self.medical_charge
            total += amount_charged
            return total
        total += self.patient.consultation

        return total

     # where the error is coming from
    def save(self, *args, **kwargs):
        """ override the save method to dynamically save the 
        total and slug in the db whenever form_valid() of the patient is 
        checked. """
        
        self.total = self.get_total_charge()
        self.slug = slug_modifier()
        return super().save(self, *args, **kwargs)

我的看法:



class PatientCreateView(OrganizerPharmacistLoginRequiredMixin, CreateView):
    """ Handles request-response cycle made by the admin/pharmacists to create
    a patient"""

    template_name = 'pharmcare/patients/patient-info-create.html'
    form_class = PatientModelForm
    # queryset = Patient.objects.all()

    def get_queryset(self):

        organization = self.request.user.userprofile
        user = self.request.user
        if user.is_organizer or user.is_pharmacist:
            queryset = Patient.objects.filter(
                organization=organization)
        else:
            queryset = Patient.objects.filter(
                pharmacist=user.pharmacist.organization
            )
            queryset = queryset.filter(pharmacist__user=user)

        return 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.save()

        # Patient.objects.get_or_create(pharmacist=user.pharmacist.organization)
        return super(PatientCreateView, self).form_valid(form)

    def get_success_url(self) -> str:
         return reverse('pharmcare:patient-info')


我的开发环境中的错误消息:


IntegrityError at /pharmcare/patient-info-create/
UNIQUE constraint failed: pharmcare_patient.id
Request Method: POST
Request URL:    http://127.0.0.1:8000/pharmcare/patient-info-create/
Django Version: 4.2
Exception Type: IntegrityError
Exception Value:    
UNIQUE constraint failed: pharmcare_patient.id
Exception Location: C:\Users\USER\Desktop\dj-tests\env\Lib\site-packages\django\db\backends\sqlite3\base.py, line 328, in execute
Raised during:  pharmcare.views.patients.PatientCreateView
Python Executable:  C:\Users\USER\Desktop\dj-tests\env\Scripts\python.exe
Python Version: 3.12.0
Python Path:    
['C:\\Users\\USER\\Desktop\\dj-tests',
 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python312\\python312.zip',
 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python312\\DLLs',
 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python312\\Lib',
 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python312',
 'C:\\Users\\USER\\Desktop\\dj-tests\\env',
 'C:\\Users\\USER\\Desktop\\dj-tests\\env\\Lib\\site-packages',
 'C:\\Users\\USER\\Desktop\\dj-tests\\env\\Lib\\site-packages\\win32',
 'C:\\Users\\USER\\Desktop\\dj-tests\\env\\Lib\\site-packages\\win32\\lib',
 'C:\\Users\\USER\\Desktop\\dj-tests\\env\\Lib\\site-packages\\Pythonwin']
Server time:    Sat, 30 Dec 2023 18:02:51 +0000

我也尝试过使用Django

self.object
提供的
CBV
,并且我尝试在stackoverflow中查看与我的问题相关的先前问题,但没有人能够解决我的问题,其中80%使用SET_NULL在他们的外键上,我不想要。

请我需要你关于完成这项工作的答案,因为它有点阻碍了我一天的工作进度。谢谢!

python django postgresql django-orm django-class-based-views
1个回答
0
投票

使用以下代码。

def save(self, *args, **kwargs):
    """ override the save method to dynamically save the 
    total and slug in the db whenever form_valid() of the patient is 
    checked. """
        
    self.total = self.get_total_charge()
    self.slug = slug_modifier()
    obj = super(Patient, self).save(*args, **kwargs)
    return obj

© www.soinside.com 2019 - 2024. All rights reserved.