TypeError:“ FieldFile”对象不可调用

时间:2019-06-18 13:39:59

标签: django-rest-framework

尝试获取上传文件的网址时,我得到了TypeError: 'FieldFile' object is not callable

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?

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分:0)

按照书面规定,您正在尝试在此行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