类型错误:“FieldFile”对象不是可调用(TypeError: 'FieldFile&

2019-10-29 13:36发布

我得到的TypeError: 'FieldFile' object is not callable试图获得上传文件的URL时:

class FetchedDataSerializer(serializers.ModelSerializer):
   file_fields = serializers.SerializerMethodField()

   class Meta:
      model = FetchedData
      fields = ('model_id', 'config_id', 'config_name', 'file_fields')

   def get_file_fields(self, obj):
      queryset = obj.config_id.config_file() ### 
      return ShoppingListSerializer(queryset, many=True).data

该模型包括以下字段:

class ShoppingList(models.Model):
   id = models.CharField(max_length=40, primary_key=True)
   name = models.CharField(max_length=40)
   session_id = models.CharField(max_length=40)
   config_file = models.FileField(upload_to=upload_config_file)

   def __str__(self):
       return self.id

我应该用做queryset ,最终显示上传的文件URL?

Answer 1:

您可以编辑get_file_fields这样的吗?

class FetchedDataSerializer(serializers.ModelSerializer):
   file_fields = serializers.SerializerMethodField()

   class Meta:
      model = FetchedData
      fields = ('model_id', 'config_id', 'config_name', 'file_fields')

   def get_file_fields(self, obj):
      queryset = ShoppingList.objects.filter(config_file = obj)
      return [ShoppingListSerializer(cf).data for cf in queryset]



Answer 2:

由于写的,你想在这一行执行现场obj.config_id.config_file() 如果你想序列化,你可以简单地序列化一个模型对象,你并不需要一个查询集。


class FetchedDataSerializer(serializers.ModelSerializer):
   file_fields = serializers.SerializerMethodField()

   class Meta:
      model = FetchedData
      fields = ('model_id', 'config_id', 'config_name', 'file_fields')

   def get_file_fields(self, obj):
      return ShoppingListSerializer(obj).data


文章来源: TypeError: 'FieldFile' object is not callable