我需要一个序列化器,在那里我可以用path_to_file获取我的文件版本,如
{
1:path_to_file,
2: path_to_file,
.... : ..........,
n_verison: path_to_file
}
models.py
class Report(models.Model):
employee = models.ForeignKey(Worker, on_delete=models.SET_NULL, null=True)
file_name = models.CharField(max_length=20, null=True)
datetime = models.DateTimeField(auto_created=True)
class ReportVersionInfo(models.Model):
report = models.ForeignKey(Report, on_delete=models.CASCADE)
version = models.IntegerField()
file = models.FileField()
def save(self, *args, **kwargs):
# This means that the model isn't saved to the database yet
if self._state.adding:
# Get the maximum display_id value from the database
last_id = self.objects.all().aggregate(largest=models.Max('version'))['largest']
# aggregate can return None! Check it first.
# If it isn't none, just use the last ID specified (which should be the greatest) and add one to it
if last_id is not None:
self.version = last_id + 1
serializer.py
from rest_framework import serializers
from django.utils import timezone
from worker.models import Worker
from report import models
class FileVersionSerializer(serializers.ModelSerializer):
class Meta:
model = models.ReportVersionInfo
fields = ['version', 'file']
read_only_fields = ['version']
class ReportsSerializers(serializers.ModelSerializer):
report_file = serializers.SerializerMethodField()
class Meta:
model = models.Report
fields = ['employee','file_name', 'report_file',]
views.py
class ReportsViewSet(viewsets.ModelViewSet):
queryset = models.Report.objects.all()
serializer_class = serializers.ReportsSerializers
我是使用drf的新手,所以我道歉,如果你认为这是一个愚蠢的问题,我尝试了所有的例子或任何serializermethods,阅读文档,并没有找到任何可以帮助我与此
1条答案
按热度按时间9ceoxa921#
您所建议的JSON响应无论从人类Angular 还是从编程Angular 都很难理解。键应该用来描述值是什么,而不是作为值本身。如果我想从这个JSON有效负载中获取文件路径,我不能简单地访问
.path_to_file
,我需要显式地知道版本号,作为获取所需数据的密钥。我建议使用以下形式的JSON payload: