我的某個模型存在問題。我正在上傳一張圖片,並且我想存儲該id(數據庫表中的pk),但我需要知道Django將在哪一點訪問self.id
。Django - 如何在保存新對象時獲取self.id?
models.py
class BicycleAdItemKind(MPTTModel):
def url(self, filename):
pdb.set_trace()
url = "MultimediaData/HelpAdImages/ItemKind/%s/%s" % (self.id, filename)
return url
def item_kind_image(self):
return '<img align="middle" src="/media/%s" height="60px" />' % self.image
item_kind_image.allow_tags = True
# Bicicleta completa, Componentes para bicicleta, Acessorios para ciclista
n_item_kind = models.CharField(max_length=50)
parent = TreeForeignKey('self', null=True,
blank=True, related_name='children')
description = models.TextField(null=True, blank=True)
image = models.ImageField(upload_to=url, null=True, blank=True)
date_inserted = models.DateTimeField(auto_now_add=True)
date_last_update = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.n_item_kind
class MPTTMeta:
order_insertion_by = ['n_item_kind']
的問題是在url()
方法;更新對象時,我只能得到self.id
,創建新對象時我沒有得到self.id
。如何修改此模型以便在創建新對象時獲得self.id
?
在當前的代碼中,當我創建一個新的對象,我會落得像一個網址:
MultimediaData/HelpAdImages/ItemKind/None/somefile.jpg
,我需要有類似:
MultimediaData/HelpAdImages/ItemKind/35/somefile.jpg
任何線索?
您可以突出顯示「url()」函數的使用位置嗎? – tushar747
它用於字段圖像中,「image = models.ImageField(upload_to = url,null = True,blank = True)」。當圖像上傳時,該方法被激活。 –