使用方法设置Django模型字段

2024-10-01 09:20:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图设置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()

Tags: inselfformaturlforgetreturntitle
3条回答
title_for_url = models.CharField(max_length=100, editable=False, default=property(_get_title_for_url)

你不能那样做default'应该是一个值或一个刻度(不带参数)。。。(属性不是可计算的)

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

^{pr2}$

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

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)

默认情况下不能使用property()

.., default=property(_get_title_for_url))

默认值应为常量。如果需要计算丢失的值,请使用pre_save钩子。在

相关问题 更多 >