[英]Query two models in Django into one queryset
I have two models in my django app:我的 django 应用程序中有两个模型:
class Person(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
persons = models.ManyToManyField(Person, related_name="books")
Now I need to create a view that will make one query for regex to both of the models, find the ones that are matching and display them in template.现在我需要创建一个视图,它将对两个模型进行一次正则表达式查询,找到匹配的模型并将它们显示在模板中。 If I do:
如果我做:
class SearchListView(ListView):
queryset = Person.objects.filter(name__icontains="a")
book_queryset = Book.objects.filter(title__icontains="a")
I get an error that ListView accepts only one queryset.我收到一条错误消息,指出 ListView 只接受一个查询集。 What is the typical solution to such problem?
此类问题的典型解决方案是什么?
You need to do something a little bit different here:你需要在这里做一些不同的事情:
class SearchListView(ListView):
queryset = Person.objects.filter(name__icontains="a")
def get_context_data(self, **kwargs):
context = super(SearchListView, self).get_context_data(**kwargs)
context['book_queryset'] = Book.objects.filter(title__icontains="a")
return context
Then in your view you can do somenting like the following:然后在您看来,您可以执行以下操作:
{% for object in object_list %}
<p>{{object}}</p>
{% endfor %}
{% for object in book_queryset %}
<p>{{object}}</p>
{% endfor %}
The reason why the way you are using is not working is because ListView
inherit from MultipleObjectMixin
the queryset
property and that property is passed to object_list
context variable in the template, that happens under the hood and if you want to pass more context variables to the template you need to follow the approach I shared.您使用的方式不起作用的原因是因为
ListView
从MultipleObjectMixin
继承了queryset
属性,并且该属性传递给模板中的object_list
上下文变量,这在幕后发生,如果您想将更多上下文变量传递给模板您需要遵循我分享的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.