我正在使用django 1.6和django-rest-framework 2.4。我有一个与另一个模型有外键关系的通用模型。通用模型显然可以与任何其他主机模型相关联。我希望能够一次性保存主机模型和通用模型及其所有关联。
例如:
models.py:
from django.db import models
from django.contrib.contenttypes.generic import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
class GenericItem(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
details = models.TextField(blank=True)
class GenericSubItem(models.Model):
generic_item = models.ForeignKey(GenericItem, null=True, blank=True, related_name="sub_items")
details = models.TextField(blank=True)
class Host(models.Model):
details = models.TextField(blank=True)
generic_items = GenericRelation(GenericItem, content_type_field='content_type', object_id_field='object_id')
serializers.py:
from rest_framework import serializers
from . import models
class GenericSubItemSerializer(serializers.ModelSerializer):
class Meta:
model = models.GenericSubItem
fields = ('id', 'details', )
class GenericItemSerializer(serializers.ModelSerializer):
sub_items = GenericSubItemSerializer(many=True, required=False, allow_add_remove=True)
class Meta:
model = models.GenericItem
fields = ('id', 'details', 'sub_items', )
class HostSerializer(serializers.ModelSerializer):
generic_items = GenericItemSerializer(many=True, required=False, allow_add_remove=True)
class Meta:
model = models.Host
fields = ('id', 'details', 'generic_items', )
views.py:
from rest_framework import viewsets
from . import serializers, models
class HostView(viewsets.ModelViewSet):
queryset = models.Host.objects.all()
serializer_class = serializers.HostSerializer
这里的问题是即使发布了sub_items,也不会保存它们。更糟糕的是,如果你通过shell添加一个子项,它将显示正常,但是当你保存时,子项将被删除。
如何编写序列化程序以便保存主机可以保存其他所有内容?
谢谢,
保
答案 0 :(得分:0)
您能否提供有关views.py
的更多详情?或者,您可以尝试覆盖create(self, validated_data)
中的GenericItemSerializer
,如下所示:
class GenericItemSerializer(serializers.ModelSerializer):
sub_items = GenericSubItemSerializer(many=True, required=False, allow_add_remove=True)
class Meta:
model = models.GenericItem
fields = ('id', 'details', 'sub_items', )
def create(self, validate_data):
subitemdata = validate_data.pop('sub_items')
subitemobj = GenericSubItem.objects.create(**subitemdata)
GenericItem.objects.create(sub_items=subitemobj, **validate_data)