我知道这个帖子已经有了答案,但我开始努力解决这个问题,因为这篇文章是我的灵感之一,所以我想分享我的最终解决方案。它可能对某人有用。我有模型,所以父类:
#parent model class
class Parent(models.Model):
id = models.AutoField(primary_key=True)
field = models.CharField(max_length=45)
class Meta:
managed = False
db_table = 'parent'
然后,子类:
#child model class
class Child(models.Model):
id = models.AutoField(primary_key=True)
field = models.CharField(max_length=45)
parent = models.ForeignKey(Parent, related_name='children')
class Meta:
managed = False
db_table = 'child'
我必须定义序列化程序,因为我不想创建一个路由器可访问的 url 来直接管理 Children 对象,但我想通过父 ModelViewSet 的 ModelViewSet 创建它们,这就是我需要的:
class ChildSerializer(serializers.ModelSerializer):
class Meta:
model = Child
read_only_fields = ('id',)
class ParentSerializer(serializers.ModelSerializer):
class Meta:
model = Banner
read_only_fields = ('id',)
class ParentSerializerNested(ParentSerializer):
children = ChildSerializer(many=True)
然后我准备创建 ModelViewSet,覆盖/扩展 create/update mixins,并使其通用,以便在其他情况下重用它:
class ParentChildViewSet(viewsets.ModelViewSet):
def create(self, request, *args, **kwargs):
serializer = self.serializer_parent(data=request.DATA,
files=request.FILES)
try:
if serializer.is_valid():
with transaction.commit_on_success():
self.pre_save(serializer.object)
parent = serializer.save(force_insert=True)
self.post_save(parent, created=True)
# need to insert children records
for child in request.DATA[self.child_field]:
child[self.parent_field] = parent.id
child_record = self.serializer_child(data=child)
if child_record.is_valid():
child_record.save(force_insert=True)
else:
raise ValidationError('Child validation failed')
headers = self.get_success_headers(serializer.data)
serializer.data[self.child_field] = self.serializer_child(
self.model_child.objects.filter(
**{self.parent_field: parent.id}).all(),
many=True).data
return Response(serializer.data,
status=status.HTTP_201_CREATED,
headers=headers)
except ValidationError:
pass
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
因此,我可以在我的应用程序中的每个嵌套关系案例中重用它,如下所示:
class ParentViewSet(ParentChildViewSet):
child_field = 'children'
parent_field = 'parent'
model = Parent
model_child = Child
serializer_class = ParentSerializerNested
serializer_parent = ParentSerializer
serializer_child = ChildSerializer
最后,路由:
router = routers.DefaultRouter()
router.register(r'parents', ParentViewSet)
它就像一个魅力!