基本Python、Django、DRY-从(模型)类调用方法
我不熟悉Python和Django。我有一个基本的python/django ORM问题困扰着我。我有两个模型,它们有一个重复的show_图像功能。那不好基本Python、Django、DRY-从(模型)类调用方法,python,django,django-models,dry,Python,Django,Django Models,Dry,我不熟悉Python和Django。我有一个基本的python/django ORM问题困扰着我。我有两个模型,它们有一个重复的show_图像功能。那不好 class Dinner(models.Model): title = models.CharField(max_length=200) is_approved = models.BooleanField() hero = models.ImageField(upload_to="heros", blank=True
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
然后在我的模型中,我尝试:
test(self.hero)
得到了这个(而不是值):
如何从中获取值,以便检查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
class扬声器(models.Model):
title=models.CharField(最大长度=200)
传记=模型.TextField(空白=真)
headshot=models.ImageField(上传到=上传到,空白=真)
测试(头像)
def显示_图像(自身):
image\u url=None
如果self.headshot不是None:
图像\ url=“”。格式(基本\ url,self.headshot)
返回图像url
show_image.short_description=“缩略图”
show_image.allow_tags=True
您在类级别调用该测试方法,这毫无意义。这意味着它是在定义模型类时执行的,这就是您看到field类的原因。当定义模型时,会发生大量元类的事情,所以当你得到一个实例时,你会看到值,而不是字段类——但是在你调用方法的时候,这并没有发生
在任何情况下,您都需要用模型的实例调用它,这样实际上就有一个值需要处理
我怀疑您对Python相当陌生,所以这里有一个提示:您可以从Python shell中检查所有这些内容。启动
/manage.py shell
,然后导入您的模型,实例化一个(或从数据库中获取),然后您可以使用dir()
等方法检查它。比在代码中编写调试函数效率更高。看起来您是在模型类的hero
属性上调用test
函数,而不是在模型实例上。更多的代码上下文可能有助于确认这一点。您需要准确地显示调用test
的方式和位置。“在我的模型中我尝试过”是不够的信息。在我的模型中。模型类本身。“在我的模型中。模型类本身”仍然不能解释你的意思。哪里显示代码@DanielRoseman Edit显示我调用test()的位置。我明白了。谢谢你的回答,它回答了我发布的问题。
django.db.models.fields.files.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