首页 > 解决方案 > 如何从Django中的数据库中获取另一个应用程序的值?

问题描述

如何从另一个应用程序获取值并在 Django 项目的另一个应用程序中存在的模板中显示该值?我有这个项目目录结构: -

-News-Scrape
  - accounts
  - education
  - home
  - news
    - models.py(The value is present here)
    - views.py
    - templates
  - static
  - templates
    - base.html(I want to display a value here which is present in the `news` app)

由于base.html文件不在应用程序中,我如何news在此页面中显示应用程序数据库中的任何特定值。

这是models.py(来自新闻应用程序)文件:-

from django.db import models

class PageView(models.Model):
    hits    =   models.IntegerField(default=0) #I need this value to be displayed in my `base.html` file

这是views.py(来自新闻应用程序)文件:-

def news_list(request, *args, **kwargs):
    if(PageView.objects.count()<=0):
        x=PageView.objects.create()
        x.save()
    else:
        x=PageView.objects.all()[0]
        x.hits=x.hits+1
        x.save()
    context={}

    context = {
       'object_list': queryset,
       'page': x.hits
    }
    return render(request, 'news_list.html', context)

如果base.html文件在news应用程序内部,我可以轻松地通过 获取值,但是当文件存在于应用程序外部{{object.<id_label>}}时,这不起作用。base.html我是 Django 的初学者,很难找到实现这一目标的方法。

标签: pythondjango

解决方案


新闻-刮

  • accounts
  • education
  • home
  • news
    • templates
      • news
        • base.html或您的 html 文件
    • models.py
    • views.py

您可以为项目中的每个应用程序创建单独的模板文件夹


推荐阅读