在视图Django中声明类的Instant

时间:2019-02-07 14:24:39

标签: python django

我的模型中有以下模型。py

class Grade(models.Model):
    grade = models.IntegerField()

class Student(models.Model):
    name = models.CharField(max_length=255) 
    grade = models.ForeignKey(Grade)
    rollno = models.BigIntegerField()

我想在view.py中为Student类做post方法。

如果没有外键,则非常简单,如下所示;

class RegisterStudent(generics.ListAPIView):
    '''
    GET student/
    POST student/
    '''
    queryset = Student.objects.all()
    serializer_class = StudentSerializer


        def post(self, request, *args, **kwargs):

            a_site = Student.objects.create(
            name=request.data["name"],
            grade=request.data["grade"],
            rollno=request.data["rollno"],
            )
            return Response(
                data=StudentSerializer(a_site).data,
                status=status.HTTP_201_CREATED
            )

但是当我使用外键方法时,我不确定如何为学生评分。

这就是我的成绩:

class RegisterGrade(generics.ListAPIView):
    '''
    GET grade/
    POST grade/
    '''
    queryset = Grade.objects.all()
    serializer_class = GradeSerializer

    def post(self, request, *args, **kwargs):

        a_site = Grade.objects.create(
            grade=request.data["grade"],
        )
        return Response(
            data=GradeSerializer(a_site).data,
            status=status.HTTP_201_CREATED
        )

任何帮助将不胜感激。谢谢

1 个答案:

答案 0 :(得分:0)

只需获取或创建Grade并在创建Student时使用它

def post(self, request, *args, **kwargs):
    grade, created = Grade.objects.get_or_create(
        grade=int(request.data["grade"]),
    )
    student = Student.objects.create(
        name=request.data["name"],
        grade=grade,
        rollno=request.data["rollno"],
    )
    return Response(
        data=StudentSerializer(student).data,
        status=status.HTTP_201_CREATED
    )

在这里检查Grade是否已经存在,如果没有,则从数据库中获得分数,如果没有,它将创建一个新的Grade。然后,您创建一个带有grade的Student。