如何使用 django rest 框架工作获取带有用户 ID 的 s3 文件 url?

How to get s3 file url with user Id using django rest frame work?

上传图片后我的 s3 文件 URL - "https://demo-documents.s3.amazonaws.com/pics/fever.jpg" 必需 URL 是 - "https://demo-documents.s3.amazonaws.com/pics/@userId/fever.jpg"

Models.py

    class MedicalRecord(models.Model):
        title = models.CharField(max_length=200)
        date_time = models.DateTimeField()
        user = models.CharField(max_length=200)
        record_file = models.ImageField(upload_to='pic')
    
    Serializer.py
    
    class MedicalRecordModelSerializer(serializers.ModelSerializer):
        class Meta:
            model = MedicalRecord
            fields = '__all__'
    Views.py
    
    class MedicalRecordViewSet(viewsets.ModelViewSet):
        serializer_class = MedicalRecordModelSerializer
        queryset = MedicalRecord.objects.all()

您可以定义upload_to函数。

def upload_to(instance, filename):
    return 'pic/%s/%s' % (instance.user, filename)

class MedicalRecord(models.Model):
    title = models.CharField(max_length=200)
    date_time = models.DateTimeField()
    user = models.CharField(max_length=200)
    record_file = models.ImageField(upload_to=upload_to)

希望对您有所帮助。