0

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

在序列化程序中,我想检索 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。

4

0 回答 0