如何从Django中的数据库中从另一个应用程序获取值?

2024-04-24 15:14:51 发布

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

如何从另一个应用程序获取值,并在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的初学者,很难找到实现这一目标的方法


Tags: 文件项目djangopy应用程序baseobjectsvalue