模型具有以下关系:
class ShoppingList(models.Model):
(...)
config_file = models.FileField(upload_to=upload_config_file)
class FetchedData(models.Model):
(...)
config_id = models.ForeignKey(ShoppingList, on_delete=models.CASCADE, default=0)
def config_link(self):
return self.config_id.config_file
然后,在serializers.py
中:
class FetchedDataSerializer(serializers.ModelSerializer):
file_link = serializers.SerializerMethodField()
class Meta:
model = FetchedData
fields = ('config_id', 'file_link')
def get_file_link(self, obj):
return obj.config_link()
问题是,当我得到响应时,文件被表示为它们的内容,因此,对于JSON文件,我会得到类似的东西:
{
"config_id": "4544",
"file_link": [
"{\r\n",
" \"glossary\": {\r\n",
" \"title\": \"example glossary\",\r\n",
"\t\t\"GlossDiv\": {\r\n",
" \"title\": \"S\",\r\n",
"\t\t\t\"GlossList\": {\r\n",
" \"GlossEntry\": {\r\n",
" \"ID\": \"SGML\",\r\n",
"\t\t\t\t\t\"SortAs\": \"SGML\",\r\n",
"\t\t\t\t\t\"GlossTerm\": \"Standard Generalized Markup Language\",\r\n",
"\t\t\t\t\t\"Acronym\": \"SGML\",\r\n",
"\t\t\t\t\t\"Abbrev\": \"ISO 8879:1986\",\r\n",
"\t\t\t\t\t\"GlossDef\": {\r\n",
" \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\",\r\n",
"\t\t\t\t\t\t\"GlossSeeAlso\": [\"GML\", \"XML\"]\r\n",
" },\r\n",
"\t\t\t\t\t\"GlossSee\": \"markup\"\r\n",
" }\r\n",
" }\r\n",
" }\r\n",
" }\r\n",
"}"
]
}
该如何仅接收文件位置链接?
答案 0 :(得分:1)
在您的config_link
方法定义中,您将返回相关的config
的{{1}},它实际上是文件对象本身。
您应该返回文件url,它是文件的file
属性:
url