有两个模型,它们是通过这种方式定义的:
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
class FetchedData(models.Model):
model_id = models.CharField(max_length=40)
config_id = models.ForeignKey(BillOfMaterial, on_delete=models.CASCADE, default=0)
config_name = models.CharField(max_length=40)
def __str__(self):
return self.model_id
并像这样序列化:
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):
print(obj)
# queryset = ShoppingList.objects.filter(config_file = obj) ## (1)
queryset = BillOfMaterial.objects.all() ## (2)
return [ShoppingListSerializer(cf).data for cf in queryset]
建议我*在上面的序列化器中实现标记为(1)的解决方案,但是当它打开时,我得到的响应为空数组,例如:
[
{
"model_id": "6553",
"config_id": "2322",
"config_name": "Config No. 1",
"file_fields": []
}
]
同时,在选项(2)打开且选项(1)被注释掉的情况下,我得到了所有显示的实例:
[
{
"model_id": "6553",
"config_id": "2322",
"config_name": "Config No. 1",
"file_fields": [
{
"id": "2322",
"name": "First Example",
"session_id": "9883",
"config_file": "/uploads/2322/eq-example_7DQDsJ4.json"
},
{
"id": "4544",
"name": "Another Example",
"session_id": "4376",
"config_file": "/uploads/4544/d-jay12.json"
}
]
}
]
print(obj)
方法始终提供一个model_id
值。我猜它应该输出file_fields.id
。
我应该如何重新构建这段代码,使其仅显示file_field
与id
匹配父级config_id
的情况?
*这是此处描述的问题的后续内容:TypeError: 'FieldFile' object is not callable
答案 0 :(得分:0)
在FetchedData
模型中,我添加了此方法:
def config_link(self):
return self.config_id.config_file
(它绑定了config_file
模型中的ShoppingList
)。
FetchedDataSerializer
应该看起来像这样:
class FetchedDataSerializer(serializers.ModelSerializer):
file_link = serializers.SerializerMethodField()
class Meta:
model = FetchedData
fields = ('model_id', 'config_id', 'config_name', 'file_link')
def get_file_link(self, obj):
return obj.config_link()