1

简介:我有 2 个 Django Rest Framework 模型Patient,并且Embryo只有 1 个用户是超级用户。所有患者都属于超级用户。一个病人可以有很多个胚胎,但每个胚胎只能有一个病人。

我想要做什么:我正在尝试在创建或更新患者模型或胚胎模型时向患者发送电子邮件。下面是我的代码我做错了什么

下面是我的views.py

 def send_email_confirmation(instance):
    patient = Patient.objects.get(id=instance)
    embryo = Embryo.objects.filter(patient=patient)
    try:
        '''Sending the Order to the patient'''
        subject = "Gemonic Prediction Create or Update record"
        to = ['{}'.format(patient.email)]
        from_email = "no_reply@genomicprediction.com/"
        order_information = {
            'patient': patient,
            'embryo': embryo
        }
        message = get_template('email/email.html').render(order_information)
        msg = EmailMessage(subject, message, to=to, from_email=from_email)
        msg.content_subtype = 'html'
        msg.send()
    except IOError as e:
        return e


class PatientsApiView(viewsets.ModelViewSet):
    """Handles Creating, reading and updating Patients"""

    serializer_class = serializers.PatientsSerializer
    queryset = Patient.objects.all()
    authentication_classes = (TokenAuthentication,)
    filter_backends = (filters.SearchFilter,)
    permission_classes = (IsAuthenticated,)
    search_fields = ("first_name", "last_name", "phone", "email",)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)
        instance = serializer.save()
        try:
            send_email_confirmation(created=instance)
            print('An email has been sent to the customer.')
        except IOError as e:
            return e

    def perform_update(self, serializer):
        instance = serializer.save()
        try:
            send_email_confirmation(modified=instance)
            print('An email has been sent to the customer.')
        except IOError as e:
            return e


class EmbroApiView(viewsets.ModelViewSet):
    """Handles Creating, reading and updating Patients"""

    serializer_class = serializers.EmbryoSerializer
    queryset = Embryo.objects.all()
    authentication_classes = (TokenAuthentication,)
    filter_backends = (filters.SearchFilter,)
    permission_classes = (IsAuthenticated,)
    search_fields = ("code_name", "karyotype", "sex", "down_syndrome",)

    def perform_create(self, serializer):
        serializer.save(pk=self.kwargs.get("pk"))
        instance = serializer.save()
        try:
            send_email_confirmation(created=instance)
            print('An email has been sent to the customer.')
        except IOError as e:
            return e

    def perform_update(self, serializer):
        instance = serializer.save()
        try:
            send_email_confirmation(modified=instance)
            print('An email has been sent to the customer.')
        except IOError as e:
            return e

我的模型在下面以防万一

class Patient(models.Model):
    """Patients model which has all the patients information"""
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=25)
    last_name = models.CharField(max_length=35)
    phone = models.CharField(max_length=18)
    email = models.EmailField(unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    @property
    def full_name(self):
        return "%s %s" % (self.first_name, self.last_name)

    def __str__(self):
        return "%s %s" % (self.full_name, self.email)


class Embryo(models.Model):
    """A ForeignKey model to the patient"""
    patient = models.ForeignKey(Patient, related_name="embryos", on_delete=models.CASCADE)
    code_name = models.CharField(max_length=100)
    karyotype = models.CharField(max_length=100)
    down_syndrome = models.BooleanField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    GENDER_CHOICES = (
        ("M", "Male"),
        ("F", "Female"),

    )
    sex = models.CharField(blank=True, null=True, max_length=1, choices=GENDER_CHOICES)
4

2 回答 2

1

您可以使用 django 的信号。

模型更改时发出信号。这是官方文档https://docs.djangoproject.com/en/2.1/topics/signals/

于 2018-11-05T16:39:38.340 回答
0

在类EmbroApiView中,方法perform_updateperform_create正在调用send_email_confirmation的实例Patient(在序列化程序上调用 save 的结果)。在函数内部send_email_confirmation,第一行是

patient = Patient.objects.get(id=instance)

因此,您使用的Patient是 id 的实例,这是我看到的第一个错误。

第二个类似,但EmbroApiView在这种情况下,对于类,您send_email_confirmation使用Embryo.

于 2018-11-05T16:48:41.260 回答