在数据库中存储应用程序常量

时间:2011-04-05 16:49:59

标签: python django django-views

我正在创建一个小博客应用。以下是我的观点摘录: views.py

from django.shortcuts import render_to_response
from blog.post.models import Post, Comment
from django.contrib.auth.models import User
from django.http import Http404

PAGE_SIZE = 5
ABSTRACT_CONTENT_SIZE = 300

def main(request, page = 0):
    post_objects = Post.objects.filter(visible = True)[page : page + PAGE_SIZE]
    posts = []
    for p in post_objects:
        if len(p.content) > ABSTRACT_CONTENT_SIZE:
            abstract = p.content[:ABSTRACT_CONTENT_SIZE] + '...'
        else:
            abstract = p.content
        posts.append({
        'subject': p.subject,
        'content': abstract,
        'author': p.author,
        'date': p.date,
        'noc': p.number_of_comments,
        'number': p.pk
        })
    return render_to_response('main.html',{'posts': posts})

我想将这两个常量放入数据库(以后我可以从管理员处理它们)。问题是,我应该如何在视图中加载它们,或者可能有另一种方法来执行此任务?提前谢谢。

2 个答案:

答案 0 :(得分:4)

class SiteSettings(models.Model):
      value = models.IntegerField() # Assuming you are only using integer value 
      type  = models.CharField(unique=True) # could also make this the primary key


PAGE_SIZE = SiteSettings.Objects.filter(type="page_size").get()  
# you should be able to do this as well since type is unique
PAGE_SIZE = SiteSettings.Objects.get(type="page_size")
PAGE_SIZE.value

答案 1 :(得分:1)

检查all this configuration apps以在您的数据库中存储站点信息