【问题标题】:ModelSerializer 'TypeError: "ReturnList" is not callable' with many=TrueModelSerializer 'TypeError: "ReturnList" is not callable' with many=True
【发布时间】: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


    【解决方案1】:

    只需从 '.data()' 中删除括号,它应该可以工作。 ReturnDict 和 ReturnList 是序列化程序的返回类型,它们不是可调用的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-31
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      • 1970-01-01
      • 2022-08-23
      • 2022-12-26
      相关资源
      最近更新 更多