gpt4 book ai didi

python - Django:搜索相关模型

转载 作者:太空宇宙 更新时间:2023-11-04 11:18:10 31 4
gpt4 key购买 nike

您好,我想创建一个简单的搜索表单,以便从相关模型中获取数据。

我有 3 个模型:

class Person(models.Model):
name = models.CharField()
surname = models.CharField()

class Phone(models.Model):
person = models.ForeignKey(Person,on_delete=models.CASCADE,related_name="phones")
phone = models.CharField(0

class Email(models.Model):
person = models.ForeignKey(Person,on_delete=models.CASCADE, related_name="emails")
email = models.EmailField()

在我的主视图中我有:

def home(request):
people = Person.objects.all()
query = request.GET.get("q")
if query:
people = Person.objects.filter(Q(name__icontains=query)|Q(surname__icontains=query)|
Q(emails__contains=query)|Q(phones__icontains=query))
//when I try emails_email__icontains=query I get error about no such fields

return render(request,'app/home.html',{'users': people})

它工作正常,但我也想通过电子邮件和电话进行搜索(人们可以拥有很少的电子邮件和电话)。如果在我的查询中我使用另一个 OR (|),我会收到错误消息,我无法在一个查询中组合 2 个模型。我也想尝试链:

people= above query
emails = Email.objects.filter(email__icontains=query)
context = chain(people,emails)

不幸的是,这个解决方案也行不通。我该如何解决这个问题?

编辑:模板

{% block content %}
{%for user in users %}
{{user.id }} {{user.name}} {{user.surname}}
{% for email in user.email_set.all %}
{{email}}
{% endfor %}
{% endfor %}

最佳答案

试试这个

在模型中

class Person(models.Model):
name = models.CharField()
surname = models.CharField()

class Phone(models.Model):
person = models.ForeignKey(Person,on_delete=models.CASCADE, related_name='a')
phone = models.CharField(0

class Email(models.Model):
person = models.ForeignKey(Person,on_delete=models.CASCADE, related_name='b')
email = models.EmailField()

在过滤器中

from django.db.models import Q

people = Person.objects.filter(Q(name__icontains=query)|Q(surname__icontains=query)|Q(b__email__icontains=query))

在模板中

{% block content %}
{% for user in users %}
{{user.id }} {{user.name}} {{user.surname}}
{% for email in user.b.all %}
{{email.email}}
{% endfor %}
{% endfor %}

希望对你有帮助

关于python - Django:搜索相关模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56560704/

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