Django检查post方法中的对象是否有特定值

wvt8vs2t  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(171)

我正在使用DRF并且有一个带有ManyToMany字段的对象。我想检查用户在服务器上发送的对象是否在该字段中包含任何pk。然后我想在链接到该ManyToMany的对象中将布尔字段设置为true。
型号:

class Parent(models.Model):
    child_link = models.ManyToManyField(child, related_name="child")

class Child(models.Model):
    in_use = models.BooleanField(default=False)

意见:

class ParentView(viewsets.ModelViewSet):
    serializer_class = ParentSerializer
    authentication_classes = (SessionAuthentication, )

    def get_queryset(self):
        user = self.request.user
        return Parent.objects.filter(user=user)

class ChildView(viewsets.ModelViewSet):
    serializer_class = ChildSerializer
    authentication_classes = (SessionAuthentication, )

    def get_queryset(self):
        user = self.request.user
        return Child.objects.filter(user=user)

序列化器:

class ParentSerializer(serializers.ModelSerializer):

    class Meta:
        model = Parent
        fields = __all__

class ChildSerializer(serializers.ModelSerializer):

    class Meta:
        model = Child
        fields = __all__
daolsyd0

daolsyd01#

在我描述的这个特定案例中,最好的解决方案是将create()添加到父序列化器中:

class ParentSerializer(serializers.ModelSerializer):
  def create(self, *args, **kwargs):
        if len(self.data["child_link"]) != 0:
            for id in self.data["child_link"]:
                obj = Child.objects.get(pk=id)
                obj.in_use = True
                obj.save()

        return super().create(*args, **kwargs)
   class Meta:
        model = Parent
        fields = __all__

相关问题