gpt4 book ai didi

python - 如何在 View 中对多个 Django 模型运行查询

转载 作者:行者123 更新时间:2023-12-01 08:29:06 26 4
gpt4 key购买 nike

如何对多个 Django 模型运行查询并通过模板显示它们?

我创建了两个模型,我可以独立查询它们并在各自的模板中呈现响应。但是,我想要做的是通过 Django 表单提交查询,针对两个模型运行查询,然后将结果(如果有)显示在单个模板上。我怎样才能实现这个目标?

型号:

class State(models.Model):
text = models.TextField(null=True)
topic_list = models.TextField(null=True)

class Hearings(models.Model):
url = models.TextField(primary_key=True)
title = models.TextField(null=True)
text = models.TextField(null=True)

观看次数:

def state(request,query):
data = state.objects.filter(text__icontains=query).values('text','topic_list')
return render(request,'State.html',context={'data':data})

def hearings(request,query):
data = Hearings.objects.filter(data__icontains=query).values('url','title', 'text')
return render(request,'Hearings.html',context={'data':data})

目前,我可以通过我的 View 单独查询模型。我想通过单个 View 针对两个模型运行查询。我该怎么做?

最佳答案

我不太清楚您想要实现的目标,但我会尝试回答。

How can I run a query against multiple Django models and display them through a template?

简单的答案是,您可以根据需要对 View 函数或类中的任意多个模型运行查询,并将它们添加到要传递到模板的上下文中。

例如:

def my_view(request):
context = {}
context['people'] = People.objects.all()
context['pets'] = Pet.objects.all()
return render(request, index.html, context)

在您的模板中,您可以通过 {{ people }}{{ pets }} 访问查询结果并循环访问它们等。您可以制作更多使用Q对象进行复杂的查找。 https://docs.djangoproject.com/en/2.1/topics/db/queries/#complex-lookups-with-q-objects

[..] what I want to do is submit my query through my Django form

同样,您可以从表单提交中获取数据并将其放入查询中

def user_input(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
context = {}
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
pet_name = form.cleaned_data.get('pet_name') # get the name entered into the pet name form field
person_name = form.cleaned_data.get('person_name')
context['pets'] = Pet.objects.filter(name=pet_name)
context['people'] = Person.objects.filter(name=person_name)
return render(request, index.html, context)
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})

您将再次通过传递给模板的上下文访问返回的查询。还可以使用 Q 对象构建复杂的查询。有关信息,请参阅文档 https://docs.djangoproject.com/en/2.1/topics/forms/#the-view

关于python - 如何在 View 中对多个 Django 模型运行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54013258/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com