我是 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