模型中的函数无法识别

时间:2014-06-16 18:23:01

标签: django django-models

我尝试扩展已有的模型,因此我添加了缩略图'进去。不幸的是,与此相关的功能无法识别,django控制台给了我:

thumbnail = models.ImageField(upload_to=_get_upload_image, blank=True, null=True)
NameError: name '_get_upload_image' is not defined

有人可以帮我解决这个问题吗?

Django 1.6.5 models.py(短版)

class Feed(models.Model):
    link = models.CharField(blank=True, max_length=450)
    url = models.CharField(blank=True, max_length=450)
    title = models.CharField(blank=True, null=True, max_length=250)
    category = models.ForeignKey(Category, blank=True, null=True)
    user = models.ForeignKey(User, blank=True, null=True)
    last_update = models.DateField(blank=True, null=True, editable=False)
    country = models.ForeignKey(Country, blank=True, null=True)
    thumbnail = models.ImageField(upload_to=_get_upload_image, blank=True, null=True)

    class Meta:
        unique_together = (
            ("url", "user"),
        )

    def _get_upload_image(instance, filename):
        return "images/%s_%S" % (str(time()).replace('.','_'), filename)

1 个答案:

答案 0 :(得分:0)

我通过将函数放在类

之上来解决这个问题
class Feed(models.Model):

    def _get_upload_image(instance, filename):
        return "images/%s_%S" % (str(time()).replace('.','_'), filename)

    link = models.CharField(blank=True, max_length=450)
    url = models.CharField(blank=True, max_length=450)
    title = models.CharField(blank=True, null=True, max_length=250)
    category = models.ForeignKey(Category, blank=True, null=True)
    user = models.ForeignKey(User, blank=True, null=True)
    last_update = models.DateField(blank=True, null=True, editable=False)
    country = models.ForeignKey(Country, blank=True, null=True)
    thumbnail = models.ImageField(upload_to=_get_upload_image, blank=True, null=True)