用方法设置Django模型字段

时间:2009-11-14 19:08:43

标签: python django

我正在尝试设置title_for_url,但它在我的数据库中显示为“<property object at 0x027427E0>”。我做错了什么?

from django.db import models

class Entry(models.Model):

    def _get_title_for_url(self):
        title = "%s" % self.get_title_in_url_format()
        return title

    AUTHOR_CHOICES = (('001', 'John Doe'),)
    post_date = models.DateField()
    author = models.CharField(max_length=3, choices=AUTHOR_CHOICES)
    title = models.CharField(max_length=100, unique=True)
    body = models.TextField()
    image = models.ImageField(upload_to='image/blog')
    image.blank = 'true'
    title_for_url = models.CharField(max_length=100, editable=False, default=property(_get_title_for_url))

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return "/blog/%s/" % self.get_title_in_url_format()        

    def get_title_in_url_format(self):
        "Returns the title as it will be displayed as a URL, stripped of special characters with spaces replaced by '-'."
        import re
        pattern = re.compile( '(\'|\(|\)|,)' )
        titleForUrl = pattern.sub('', self.title)
        pattern = re.compile( '( )' )
        titleForUrl = pattern.sub('-', titleForUrl)
        return titleForUrl.lower()

3 个答案:

答案 0 :(得分:3)

title_for_url = models.CharField(max_length=100, editable=False, default=property(_get_title_for_url)

你不能这样做..'default'应该是一个值或一个calable(没有args)......(属性 calable)

在您的情况下,您需要更新保存方法:

class Entry(models.Model):
    def save(self, *args, **kwargs):
       self.title_for_url = self.get_title_in_url_format()
       super(Entry, self).save(*args, **kwargs)

答案 1 :(得分:0)

您无法在默认值中使用property()

.., default=property(_get_title_for_url))

默认值应为常量。如果需要计算缺失值,请使用pre_save hook。

答案 2 :(得分:0)

这是对我有用的最终版本:

def save(self, *args, **kwargs):
    self.title = self.title.strip()
    self.title_for_url = self.get_title_in_url_format()
    super(Entry, self).save(*args, **kwargs)