我想设置我的Django模型以使用自定义路径和文件名上传文件,而我的当前模型则是这样:
def update_filename(instance, filename):
path = "accounts/"
format = instance.id + "/" + filename
return os.path.join(path, format)
class AccountsModel(models.Model):
ChannelName = models.CharField(max_length=100, unique=False)
AuthUri = models.CharField(max_length=250, unique=True)
ClientSecret = models.CharField(max_length=250, unique=True)
ClientID = models.CharField(max_length=250, unique=True)
ClientSecrets = models.FileField(upload_to="accounts/", default='', null=True, blank=False)
RequestToken = models.FileField(upload_to="accounts/", default='', null=True, blank=False)
Note = models.CharField(max_length=250, unique=False)
counter = models.IntegerField(default=0)
author = models.ForeignKey(User, null=True, blank=True, on_delete=models.PROTECT)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
当我尝试上传文件时,我想像这样:
/accounts/22/clientsecret.json
/accounts/22/token.json
我的当前配置返回此错误:
UNIQUE constraint failed: myupload_accountsmodel.ClientID
我该怎么做?我在哪里错了?
完整的项目:https://github.com/scaltro/youtubeapp/blob/master/myupload/models.py
答案 0 :(得分:0)
我在这里演示一个最小的示例(通过使用 TextBox.Text
)
DRF
# your models.py
class MyModel(models.Model):
name = models.CharField(max_length=123)
myfile = models.FileField(upload_to='account/')
# serializer.py
class MySerializer(serializers.ModelSerializer):
custom_name = serializers.CharField(write_only=True)
class Meta:
model = MyModel
fields = '__all__'
def create(self, validated_data):
validated_data['myfile'].name = validated_data.pop('custom_name')
return MyModel.objects.create(**validated_data)