如何自定义更改django中数据格式的模型或管理器?

时间:2015-04-18 11:46:14

标签: python django django-models

我有一个Article模型,包含一个title列,可以与白色空间混合存储,我想要的是,每当我查询文章时,{{1}中的空格可以使用破折号重新设置内容,以便网址友好。

models.py:

title

我的view.py:

class Article(models.Model):
    STATUS = (
        (0,'on'),
        (1,'off')
    )
    #id = models.IntegerField(primary_key=True,help_text='primary key',auto_created=True)
    category = models.ForeignKey(Category,related_name='articles', help_text='foreigner key reference Category')
    #author = models.ForeignKey(myadmin.User, help_text='foreigner key reference myadmin User')
    title = models.CharField(max_length=100, help_text='article title')
    description = models.TextField(help_text='article brief description')
    content = models.TextField(help_text='article content')
    like = models.IntegerField(default=0,help_text='like numbers')
    secretcode = models.CharField(max_length=512,help_text='who has the code can scan')
    status = models.IntegerField(choices=STATUS,help_text='status of the article')
    createtime = models.DateTimeField(auto_now_add=True,help_text='time that first created')
    modifytime = models.DateTimeField(auto_now=True,help_text='time when modified')

    articles = models.Manager()

    def __str__(self):
        return self.title
    class Meta:
        db_table = 'article'

我在考虑创建一个自定义管理器并定义一个转换数据的方法,但所需的查询条件来自请求,在这里,我不知道该怎么做?有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

我认为你必须使用slug字段并覆盖你的save方法以保存这样的东西:

class Article(models.Model):
    slug = models.SlugField("slug")
    category = models.ForeignKey(Category,related_name='articles', help_text='foreigner key reference Category')
  -- more fields --

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return self.slug

    def save(self, *args, **kwargs):
        if not self.slug:
             self.slug = self.title.strip(" ").replace(' ','-')
        super(Article, self).save(self, *args, **kwargs)

    @property
    def get_title(self):
        """ write python code for remove extra spaces so can can dispay your tile in html and call this method with instance when you want to print title """
        return new_title_without_extra_spaces

有关详细信息页面,您可以使用slug值来获取实例。希望这会对你有所帮助。