将应用常量存储在数据库中

2 投票
2 回答
1017 浏览
提问于 2025-04-16 15:08

我正在创建一个小博客应用。下面是我视图文件中的一段代码:

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 个回答

1

查看这些配置应用,可以帮助你把网站的相关信息存储到数据库里。

4

在编程中,有时候我们会遇到一些问题,可能是因为代码写得不够好,或者是我们对某些概念理解得不够透彻。比如说,可能会出现错误提示,或者程序运行不如预期。这时候,我们可以去一些技术论坛,比如StackOverflow,去寻找解决方案或者向其他人请教。

在这些论坛上,大家会分享自己的经验和解决问题的方法。你可以看到很多人提问,也有很多人回答,提供各种各样的建议和代码示例。通过这些交流,我们可以更好地理解编程的知识,提升自己的技能。

总之,遇到问题不要慌,去找资料、问别人,慢慢你就会变得越来越厉害!

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

撰写回答