我无法使用drf序列化程序和CreateAPIView通过请求的用户获取对象名称

时间:2019-03-27 17:33:36

标签: django-models django-rest-framework drf-queryset

我有:  object1与用户的OneToOneField,  object2和用户和object1的ForeignKeys。

在序列化程序中,我想检索object1的名称并将其作为object2中的默认名称。 createAPIView禁止获取操作,而我可以将hiddenfield与currentDefaultUser一起使用。 如何获取用户ID并使用它来检索object1? 我应该使用retreive并创建mixins吗?

模型

class Object1(models.Model):
    user= models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    object1_name = models.CharField(max_length=30, null=False)

class Object2(models.Model):
    user= models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    object1 = models.ForeignKey(Object1, on_delete=models.CASCADE)
    object2_name = models.CharField(max_length=30, null=False)

序列化器

class Object_2_Serializer(serializers.ModelSerializer):
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault())
    class Meta:
        model = Object2
        fields = ('user', 'object1_name', 'object2_name',)

观看次数

class object_2_CreateView(generics.GenericAPIView,
                     mixins.RetrieveModelMixin,
                     mixins.CreateModelMixin,
                     ):
    queryset = Object2.objects.all()
    serializer_class = Object_2_Serializer
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)
    lookup_field = 'object1_name'
    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

我想要获得object1_name。

0 个答案:

没有答案