我有这样的数据模型:
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_id
和 student_id
从此表中删除记录。现在,使用 DestroyAPIView
我可以通过 id
删除记录
,但这样做的方式不正确。如何通过多种条件从我的表中删除记录
?
最佳答案
使用DestroyAPIView
,您只能删除使用特定网址调用的实例
如果您想通过调用学生网址来删除CourseParticipant
首先创建一个 View 来获取student实例并获取其相关对象然后删除
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', )
关于django - 通过几个条件销毁APIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56816322/