2011-11-28 61 views
1

想像這樣一個模型:無法更改模型實例

class CFile(models.Model): 
    filepath = models.FileField(upload_to=...) 
    collection = models.ForeignKey("FileCollection",null=True) 
    ... # other attributes that are not relevant 

    def clean(self): 
    bname = os.path.basename 
    if self.collection: 
     cfiles = self.baseline.attachment_set.all() 
     with_same_basename = filter(lambda e: bname(e.filepath.path) == bname(self.filepath.path),cfiles) 
     if len(with_same_basename) > 0: 
     raise ValidationError("There already exists a file with the same name in this collection") 

class FileCollection(models.Model): 
    name = models.CharField(max_length=255) 
    files= models.ManyToManyField("CFile") 

我希望禁止一個的CFile的上傳,如果已經有一個CFile的使用相同的基本名稱,這是爲什麼我加了clean。問題是:

  • 我上傳的CFile,名爲file1.png - >被上傳,因爲存在
  • 具有此名稱的其他文件,我上傳其他CFile的,名稱爲file1.png - >我得到預期的錯誤我已經有一個這個名字的文件。所以,我嘗試更改文件,並上傳具有不同名稱的文件(file2.png)。問題是,我通過pdb停止清理,模型實例仍然爲file1.png。我想這會發生,因爲我的ValidationError和Django允許我「糾正我的錯誤」。問題是我無法更正它,如果我不能上傳另一個文件。我該如何處理?

編輯:這發生在管理區,抱歉忘了提前這個。我沒有任何習慣(除了inlines = [ FileInline ])。

回答

1

我認爲最清晰的方法是在模型中爲文件名聲明另一個字段,並使其對每個集合都是唯一的。像這樣:

class CFile(models.Model): 
    filepath = models.FileField(upload_to=...) 
    collection = models.ForeignKey("FileCollection",null=True, related_name='files') 
    filename = models.CharField(max_length=255) 
    ... # other attributes that are not relevant 

    class Meta: 
     unique_together = (('filename', 'collection'),) 

    def save(self, *args, **kwargs): 
     self.filename = bname(self.filepath.path) 
     super(CFile, self).save(args, kwargs) 
+0

我正在使用'RandomFileStorage',因爲可能有多個'FileCollection'具有'CFile'這個名字。所以,我認爲它不會重複。 – Geo

+0

@Tempus從未聽說過「RandomFileStorage」(並且google給了我0個結果)。但我很確定,如果有一個帶有這個名字的文件,Django會自動重命名文件。 – DrTyrsa

+0

對不起,當我寫關於RandomFileStorage的時候,電源已經關閉。它只是一個確保文件上傳到名稱隨機生成的文件夾的存儲。一個文件保持相同的名稱很重要(自動重命名不好)。 – Geo