[英]Django/Python: Calling a model/class function with an argument from Template
[英]Basic Python, Django, DRY - calling a method from a (model) class
我是Python和Django的新手。 我有一個基本的python / django ORM問題困擾着我。 我有兩個模型,他們有一個重復的show_image函數。 那不好。
class Dinner(models.Model):
title = models.CharField(max_length=200)
is_approved = models.BooleanField()
hero = models.ImageField(upload_to="heros", blank=True)
def show_image(self):
image_url = None
if self.hero is not None:
image_url = """<img src="{0}{1}" />""".format(BASE_URL, self.hero)
return image_url
show_image.short_description = "Thumbnail"
show_image.allow_tags = True
class Speaker(models.Model):
title = models.CharField(max_length=200)
biography = models.TextField(blank=True)
headshot = models.ImageField(upload_to="headshots", blank=True)
def show_image(self):
image_url = None
if self.headshot is not None:
image_url = """<img src="{0}{1}" />""".format(BASE_URL, self.headshot)
return image_url
show_image.short_description = "Thumbnail"
show_image.allow_tags = True
看起來很簡單 - 我決定開始嘗試。 我在models.py中創建了一個方法...
def test(obj):
print obj
然后在我的模特中我試過:
test(self.hero)
得到了這個(而不是值):
django.db.models.fields.files.ImageField
如何從中獲取值,以便檢查ImageField是否已填充?
編輯:
class Speaker(models.Model):
title = models.CharField(max_length=200)
biography = models.TextField(blank=True)
headshot = models.ImageField(upload_to=upload_to, blank=True)
test(headshot)
def show_image(self):
image_url = None
if self.headshot is not None:
image_url = """<img src="{0}{1}" />""".format(BASE_URL, self.headshot)
return image_url
show_image.short_description = "Thumbnail"
show_image.allow_tags = True
你在類級別調用該測試方法,這沒有任何意義。 這意味着它是在定義模型類時執行的,這就是您看到字段類的原因。 在定義模型時會發生很多元類的事情,所以當你得到一個實例時,你會看到值,而不是字段類 - 但是在你調用方法的時候還沒有發生。
在任何情況下,您都需要使用模型的實例調用它,以便實際上有一個值來處理。
我懷疑你對Python很新,所以這里有一個提示:你可以從Python shell中檢查所有這些東西。 啟動./manage.py shell
,然后導入模型,實例化一個(或從數據庫中獲取),然后用dir()
等檢查它。 比在代碼中編寫調試函數更有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.