提问人:Dagi 提问时间:11/15/2023 最后编辑:Dagi 更新时间:11/19/2023 访问量:68
我无法在跨多个模型的多个属性中开发搜索时实现 Manty to One 关系。一对多作品
I am not able to implement Manty to One relationship in developing a search in multiple attributes across multiple models. One to Many works
问:
#views.py
from django.shortcuts import render
from .forms import SearchForm
from .models import Author, Book, BookProfile
def index(request):
return render (request,'index.html')
def multiple_model_search(request):
if request.method == 'GET':
form = SearchForm(request.GET)
if form.is_valid():
query = form.cleaned_data.get('query')
author_results = Author.objects.filter(name__icontains=query)
book_title = Book.objects.filter(title__icontains=query)
book_profile = BookProfile.objects.filter(isbn__icontains=query)
context = {
'author_results': author_results,
'book_title': book_title,
'book_profile':book_profile,
}
return render(request, 'search_results.html', context)
else:
form = SearchForm()
return render(request, 'search_form.html', {'form': form})
#models.py
from django.db import models
# Create your models here.
class Author(models.Model):
name = models.CharField(max_length=100,blank=True, null=True)
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE,blank=True, null=True,)
def __str__(self):
return self.title
class BookProfile(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE,blank=True, null=True)
booktitle = models.ForeignKey(Book, on_delete=models.CASCADE,blank=True, null=True)
isbn = models.CharField(max_length=100,blank=True, null=True)
page = models.IntegerField(blank=True, null=True)
def __str__(self):
return self.isbn
#search_results.html
{% extends "base.html" %}
{% block content %}
<h6>Your search result is: </h6>
{% for author in author_results %}
<li class="h4">{{ author.name }}</li>
<li>{{ book.title }}</li>
{% endfor %}
{% for book in book_title %}
<li>{{book.title}}</li>
<li>by: {{book.author}}</li>
{% endfor %}
{% for book in book_profile %}
<li>{{ book.booktitle }}</li>
<li>{{ book.author}}</li>
<li>{{ book.isbn }}</li>
{% endfor %}
{% endblock %}
######################################################### 我正在做一个搜索应用程序,它允许用户使用他们的财产和作者搜索书籍。所以它是“跨多个模型的多个属性”。问题是我不能进行一对多关系搜索。多对一有效。我想检索一位作者写的书。当我搜索书籍时,它显示作者、isbn、页面。但是当我搜索作者时,无法获得书籍。
答:
0赞
inquirer
11/19/2023
#1
要通过主模型访问辅助模型:模型名称小写,_set前缀。如果您指定了related_name,则这将是您在related_name中指定的内容。
文档:“反向”跟踪关系
author = Author.objects.get(pk=1)
for i in author.book_set.all():
print(i)
相反,我们正在寻找某个作者的书籍。在辅助模型中,我们使用与主模型关联的字段,并通过双下划线写入主模型的字段。Book
author
name
book_author = Book.objects.filter(author__name=author's name)
评论
{}