【发布时间】:2017-10-31 17:52:35
【问题描述】:
我正在尝试从模型 ObjectTag 序列化查询集,然后使用它来序列化另一个模型中的反向通用关系。但是,当使用 many=True 和查询集或序列化一个实例时,这个简单的 ModelSerializer 会给我带来问题。
我有一个模型序列化器如下:
from rest_framework import serializers
from . import models
class ObjectTagSerializer(serializers.ModelSerializer):
class Meta:
model = models.ObjectTag
fields = ('tag_content_type', 'object_id', 'object_content_type')
模型定义如下:
class ObjectTag(models.Model):
"""
Many to many to attach tags to objects.
"""
object_content_type = models.ForeignKey(
ContentType,
related_name="object_object_tag" # necessary to avoid clash in ContentType
)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('object_content_type', 'object_id')
tag_content_type = models.ForeignKey(
ContentType,
limit_choices_to={
"model__in": tags.TagManager.tag_class_names,
"app_label": tags.TagManager.app_label
},
related_name="tag_object_tag" # necessary to avoid clash in ContentType
)
tag_id = models.PositiveIntegerField()
content_tag = GenericForeignKey('tag_content_type', 'tag_id')
class Meta:
unique_together = (
('tag_id', 'tag_content_type', 'object_id', 'object_content_type'),
)
def __str__(self):
return u'object tag: {tag_type}: {tag} \u21D2 {obj}'.format(
tag_type=self.content_tag._meta.verbose_name,
tag=self.content_tag,
obj=self.content_object,
)
当我尝试从模型 ObjectTag 序列化具有 many=True 的查询集时,我收到以下错误:
from .models import ObjectTag
from .serializers import ObjectTagSerializer
ot = ObjectTag.objects.filter(object_id=14691)
ObjectTagSerializer(ot, many=True, read_only=True).data()
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'ReturnList' object is not callable
当序列化一个实例时,我得到以下信息:
ObjectTagSerializer(ot[0], read_only=True).data()
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'ReturnDict' object is not callable
我正在使用 DRF 3.3.2 和 Django 1.8 和 Python 2.7.3
【问题讨论】:
标签: python django-models django-rest-framework