使用perform_create在Django + django rest框架中创建一个具有ForeignKey的对象

时间:2018-04-20 09:59:14

标签: python django python-3.x django-rest-framework

我在models.py中有以下代码段:

class Supervisor(models.Model):
    emp_id = models.ForeignKey(Employee, null=True, blank=True)

    def __str__(self):
        return '%s' % (self.supervisor)

在我看来,我做过:

class SupervisorAPIView(mixins.CreateModelMixin, generics.ListAPIView):

    """
        Add  Supervisor 
    """

  # permission_classes = (permissions.DjangoObjectPermissions,)
    lookup_field = 'pk'
    # permission_classes = (permissions.DjangoObjectPermissions,)
    serializer_class = SupervisorSerializer

    def get_queryset(self):
        return Supervisor.objects.all()

    def perform_create(self, serializer):
        serializer.save(
            emp_id=self.kwargs['pk'])



  def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

如何使用perform_create()创建超级用户对象?

0 个答案:

没有答案