通过几种条件销毁APIView

时间:2019-06-29 09:01:46

标签: django django-rest-framework

我有类似的数据模型:

from django.db import models


class Student(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField()

    def __str__(self):
        return self.first_name + ' ' + self.last_name


class Course(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
    start_date = models.DateField(null=True)
    end_date = models.DateField(null=True)

    def __str__(self):
        return self.name


class CourseParticipant(models.Model):
    course = models.ForeignKey(Course, related_name='courses', on_delete=None)
    student = models.ForeignKey(Student, related_name='students', on_delete=None)
    completed = models.BooleanField(null=True, default=False)

    def __str__(self):
        return self.course

我有一些序列化器,例如:

class AssignStudentToCourseSerializer(serializers.ModelSerializer):
    class Meta:
        model = CourseParticipant
        fields = ('id', 'student', 'course')

class UnassignedStudentFromCourseSerializer(serializers.ModelSerializer):
    class Meta:
        model = CourseParticipant
        fields = ('student_id', 'course_id')

我对此有看法

class AssignStudentToCourse(generics.CreateAPIView):
    serializer_class = AssignStudentToCourseSerializer


class UnassignedStudentFromCourse(generics.DestroyAPIView):
    serializer_class = UnassignedStudentFromCourseSerializer
    queryset = CourseParticipant.objects.all()

我有一个带有一些记录的表CourseParticipant

-------------------------------------------
| id         | course_id   | student_id   |
|------------|-------------|--------------|
| 1          |      2      |     2        |
| 2          |      3      |     2        |
| 3          |      2      |     3        |
| 4          |      2      |     4        |
-------------------------------------------

我需要通过course_idstudent_id从该表中删除记录。现在,使用DestroyAPIView,我可以通过record删除id,但是操作不正确。如何通过几种条件从表中删除record

2 个答案:

答案 0 :(得分:1)

使用DestroyAPIView只能删除使用特定URL调用的实例

如果您要通过致电学生网址来删除CourseParticipant

首先创建一个视图以获取学生实例并获取其相关对象,然后将其删除

class StudentApiView(generics.RetrieveAPIView):
    queryset = Student.objects.all()


    def get(self, request, *args, **kwargs):
        print(self.get_object(),)
        instance = self.get_object()
        course_participant_obj = CourseParticipant.objects.get(student=instance)
        course_participant_obj.delete()
        return Response('deleted', )

答案 1 :(得分:0)

我有一个类似的案例,我想向 API 端点发送一个 DELETE 方法,并让后端确定要删除的单个对象。您可以使用 DestroyAPIView 并覆盖 destroy 方法来实现此目的。

class StudentApiView(generics.DestroyAPIView):
    queryset = Student.objects.all()

    def destroy(self, request, *args, **kwargs):
        # Do logic here to get `course_participant` to delete, then
        course_participant.delete()

        # Don't return super().destroy(request, *args, **kwargs)
        return Response(status=status.HTTP_204_NO_CONTENT)