postgresql 在我的pharmcare应用程序中,“UNIQUE约束失败:pharmcare_patient.id”

6tdlim6h  于 12个月前  发布在  PostgreSQL
关注(0)|答案(2)|浏览(141)

我目前正在做一个名为pharmcare的项目,每当我想重写save()方法来插入/时,保存患者支付的total,以便创建表单或更新患者记录的药剂师不会手动执行数学运算。在view.py上没有使用我动态创建的函数来重写保存方法来解决数学问题,它执行得很好,但是在管理面板中,答案不会出现在那里。但是,如果我尝试在应用程序的models.py中使用save(),我会得到那个错误。如果我删除模型中的保存()方法,错误就会消失,这不是我想要的,因为我想它是保存在数据库立即药剂师完成创建或修改的形式。我已经使用get_or_create方法来解决它,但它仍然流产,另一个我不想用的选项(因为我希望网站所有者可以选择删除药剂师/组织者创建的记录,与他/她创建的记录一样轻松)是SET_NULLon_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 CBV提供的self.object,我也试过在stackoverflow中查看与我的问题有关的以前的问题,但没有人能够解决我的问题,其中80%的人在他们的外键上使用SET_NULL,这是我不想要的。
请我需要你的答案,使这项工作,因为它有点卡住了我的工作进展了一天了。谢谢!

pkln4tw6

pkln4tw61#

我使用了上面提供的答案,它没有工作,但它确实给了我一个提示,所以我不得不在django文档中挖掘更多(何时使用save, update,delete methods
这反而起作用:

def update(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(Patient, self).update(*args, **kwargs)

字符串
谢谢@Pycm

niknxzdl

niknxzdl2#

使用下面的代码。使用更新,而不是保存。

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).update(*args, **kwargs)
    return obj

字符串

相关问题