我有一个python 3.6 + django 1.10 + djangorestframework 3.6.4项目。 我有2个名为Report和ReportFile的Model类。我想创建CRUD操作来获取,发布和将这些文件与报告放在一起。 1报告有一个类型(这里并不重要),并且可以有许多用户应该能够上传的ReportFiles。 模型类看起来像这样:
class Report(CreationModificationMixin):
report_type = models.ForeignKey(ReportType, on_delete=models.SET_NULL,
null=True, related_name='issues',
verbose_name='Report', editable=False)
name = models.CharField(max_length=50, blank=True)
class ReportFile(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
report = models.ForeignKey(Report, on_delete=models.CASCADE, related_name='files')
uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='uploads',
null=True)
file = models.FileField(upload_to=upload_report_to, max_length=500)
和序列化程序类:
class ReportSerializer(serializers.ModelSerializer):
files = ReportFileSerializer(many=True)
formats = serializers.SerializerMethodField()
class Meta:
model = Report
fields = ('id', 'name', 'report_type', 'files')
def create(self, validated_data):
rfs_data = validated_data.pop('files')
rf = Report.objects.create(**validated_data)
for rf_data in rfs_data:
ReportFile.objects.create(Report=rf, **rf_data)
return rf
和ViewSet:
class ReportViewSet(viewsets.ModelViewSet):
serializer_class = ReportSerializer
queryset = Report.objects.all().prefetch_related('report_type')
但我无法正确上传文件。因为首先我无法使用Postman正确地上传,而且我也怀疑这是正确的方法。有人可以暗示我该怎么做吗?
非常感谢你!