【问题标题】:Django: What do I pass in as self in the view.py if I am using a function from model.py?Django:如果我使用 model.py 中的函数,我应该在 view.py 中作为 self 传递什么?
【发布时间】:2016-09-25 04:56:46
【问题描述】:

我创建了一个简单的 Django 视图,假设从我的模型中打印出名称字段列表。我在我的用户模型中创建了一个函数来查询名称,并将其附加到一个列表中,然后返回它。我想在我的视图类中调用这个函数,并将该列表作为上下文传递,以便我可以在我的模板中使用它。

以下是我当前的代码。当我试图在views.py中调用它时,我不确定self应该是什么。当我尝试传入我的模型名称用户时,它不起作用。那么在views.py 中self 到底应该是什么?在此先感谢:D

用户模型.py

def query_choice(self,query_choice):
    users_first_name = self.objects.values_list(query_choice)
    names = []
    for u in users_first_name:
        names.append(u)
    return names

views.py

def login(request):
    users_first_name = User.query_name(*self*,'first_name')
    template = loader.get_template('registration/home.html')
    context = {
        'output': users_first_name,
    }
    #return HttpResponse(output)
    return HttpResponse(template.render(context,request))

【问题讨论】:

  • 注意:您可以将 flat=true, 参数传递给 values_list,然后您的函数变成一行

标签: django django-models django-views


【解决方案1】:

您应该在模型中使用@classmethod 装饰器将query_choice 定义为类方法:

@classmethod
def query_choice(cls, query_choice):
    return cls.objects.values_list(query_choice, flat=True)

然后你可以像下面这样调用它:

names = User.query_choice("first_name")

顺便说一句,您可以使用render 来省去加载模板、渲染模板等的麻烦:

from django.shortcuts import render

def login(request):
    names = User.query_choice("first_name")
    return render(request, "registration/home.html", {"output": names})

【讨论】:

    猜你喜欢
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多