0

Djangoではモデルを使用します

class Specialist(models.Model):
    ...
    photo = models.ImageField(_('photo'), upload_to='spec_foto')
    ...

新しいオブジェクトを作成して保存すると、「写真」フィールドが .../spec_photo/filename.jpg になりますが、ファイルを .../spec_photo/ID/photo.jpg に移動したいと思います。 Specialist オブジェクトに属します。そのために、Model.save メソッドをオーバーライドします。

def save(self):
    # Saving a new object and getting ID
    super(Specialist, self).save()
    # After getting ID, move photo file to the right destination
    # ????
    # Saving the object with the right file destination
    super(Specialist, self).save()

問題は、ファイルを移動するにはどうすればよいですか? (??? コード内)。それとももっと簡単な方法がありますか?

4

2 に答える 2

-1

「upload_to」を文字列として設定する代わりに、必要なパスを返す呼び出し可能 (つまり関数) として設定できます ( https://docs.djangoproject.com/en/dev/ref/models/fields /#django.db.models.FileField.upload_to ):

class Specialist(models.Model):
    ...
    photo = models.ImageField(_('photo'), upload_to=get_file_path)
    ...

def get_file_path(instance, filename):
    if not instance.id:
        instance.save()

    return 'spec_photo/%s/photo.jpg' % instance.id
于 2013-09-10T12:08:31.873 に答える