繁体   English   中英

Basic Python,Django,DRY - 从(模型)类调用方法

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM