nae*_*ael 1 python django-models django-rest-framework
我正在尝试从模型 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')
Run Code Online (Sandbox Code Playgroud)
模型定义如下:
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,
)
Run Code Online (Sandbox Code Playgroud)
当我尝试使用模型 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
Run Code Online (Sandbox Code Playgroud)
当序列化一个实例时,我得到以下信息:
ObjectTagSerializer(ot[0], read_only=True).data()
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'ReturnDict' object is not callable
Run Code Online (Sandbox Code Playgroud)
我正在使用 DRF 3.3.2 和 Django 1.8 和 Python 2.7.3
| 归档时间: |
|
| 查看次数: |
1547 次 |
| 最近记录: |