TypeError: 'FieldFile' object is not calla

2019-08-26 12:53发布

I'm getting the TypeError: 'FieldFile' object is not callable when trying to get URL of uploaded 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):
      queryset = obj.config_id.config_file() ### 
      return ShoppingListSerializer(queryset, many=True).data

The model consists of the following fields:

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

What should be done with the queryset to eventually display uploaded file URL?

2条回答
2楼-- · 2019-08-26 13:26

As written, you are trying to execute a field in this line obj.config_id.config_file(). If you want to serialize the object you can simply serialize the one model, you don't need a queryset.


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
查看更多
时光不老,我们不散
3楼-- · 2019-08-26 13:48

Can you edit your get_file_fields like this ?

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]

查看更多
登录 后发表回答