如何在Django Rest Framework中编写涉及两个模型的业务逻辑

时间:2019-04-13 01:46:27

标签: django django-rest-framework

我很困惑,不知道如何在django和django rest框架中编写业务逻辑。

在创建学生时,如何验证注册中不存在的学生(registration_no将通过前端提供,并且将包含在json中)表?

class Student(models.Model):
    name = models.CharField(max_length=300)
    sex  = models.CharField(choices=SEX_CHOICES,max_length=255, null=True)
    Category = models.CharField(max_length=100, null=True)


    def __str__(self):
        return self.name

RegisrationModel

class Registration(models.Model):
    registration_no = models.CharField(max_length=255, unique=True)
    student = models.ForeignKey(Student, 
    on_delete= models.CASCADE, related_name='registrations')

    def __str__(self):
        return self.registration_no

1 个答案:

答案 0 :(得分:0)

如果数据库中已经存在具有相同姓名和注册号码的学生,则可以覆盖模型注册save()方法,以便进行验证并提出例外。 / p>

class Registration(models.Model):
    registration_no = models.CharField(max_length=255, unique=True)
    student = models.ForeignKey(Student, 
    on_delete= models.CASCADE, related_name='registrations')

    def __str__(self):
        return self.registration_no

    def save(self, *args, **kwargs):
        try:
            Registration.objects.get(student__name=self.name, registration_no=self.registration_no)
        except:
            super(Registration, self).save(*args, **kwargs)
        else:
            raise Exception("Student already registered")