我正在使用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__
1条答案
按热度按时间daolsyd01#
在我描述的这个特定案例中,最好的解决方案是将create()添加到父序列化器中: