在我看来,我想从数据库请求数据,在其他页面上,我也需要这些信息,但我不想再次编写这个请求逻辑.

Views.py

def account(request):
    user_id = request.user.id
    balance = Customer.objects.filter(name_id=user_id).values("usd").first()
    bonus = Customer.objects.filter(name_id=user_id).values("bonus").first()

    context1 = {'usd':balance['usd'],
                'bonus':bonus['bonus'],

    return render(request, 'account.html', context1)

def main(request):
    (here I also need to request balance and bonus)

In def main(request): and on other pages I also need balance and bonus, but I don't really want to request this values in every view.
Can I somehow write it somewhere once and to render on pages, and do not write it in every view??

推荐答案

首先,我不认为对balancebonus执行两次相同的Customer模型的查询比查询Customer实例并访问其属性customer.balance/customer.bonus更高效.

尽管如此,有两个主要选项可以使该代码可重用:

Put it in the function

def get_balance_and_bonus(request):
    customer = Customer.objects.filter(name_id=request.user.id).first()
    return customer.balance, customer.bonus

并在以下情况下使用它:

balance, bonus = get_balance_and_bonus(request)

第二种(更复杂的)方法是将所有需要客户的视图设置为make a decorator.

演绎客户的装饰师:

def add_customer(func):
    def wrap(*args, **kwargs):
        request = args[0]
        user_id = request.user.id
        kwargs['customer'] = Customer.objects.filter(name_id=user_id).first()
        return func(*args, **kwargs)
    return wrap
    

然后将其添加到需要Customer的所有函数中(请注意,在本例中,视图must中有相应的参数)

@add_customer
def account(request, customer):

    context1 = {'usd': customer.balance,
                'bonus': customer. bonus,

    return render(request, 'account.html', context1)

@add_customer
def main(request, customer):
    # here customer.balance and customer.bonus are available
    

Django相关问答推荐

使用序列化器获取Django ORM auth_user. id数据

与django相关的预取n +1问题.我该怎么解决呢?

django.template.response.ContentNotRenderedError: 必须渲染响应内容才能迭代

lower() 在 None 上被调用

Django 和 HTML 无法从指定时间开始视频

Django `UniqueConstraint` 异常处理方式与 'unique=True' 相同

Django 过滤器:过滤隐藏在多层模型 struct 中的对象

超级用户在基于类的视图中进行身份验证

在 python 视图中检测移动浏览器

如果上下文中缺少变量,如何使 Django 模板引发错误

Django 1.9:字段与父模型中不存在的字段的字段冲突

Python / Django 中的 Unicode 与 UTF-8 混淆?

如何在 Django 测试框架中修改会话

AngularJS + Django Rest Framework + CORS(CSRF Coo​​kie 没有出现在客户端)

UnicodeEncodeError:ascii编解码器无法编码字符

Django - 配置不当:模块django.contrib.auth.middleware

Django:如何过滤属于特定组的用户

Django 模型:delete() 未触发

Django REST Framework - 序列化可选字段

Django:DoesNotExist从何而来?