在开发跨多个模型的多个属性的搜索时,我无法实现Manty to One关系。一对多作品

问题描述 投票:0回答:1

#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、页数。但是当我搜索作者时,找不到书。

django search
1个回答
0
投票

通过主模型访问次模型:模型名称和_set前缀。如果您指定了 related_name,那么这将是您在 related_name 中指定的内容。

文档:“向后”遵循关系

author_results = Author.objects.get(pk=1)

for i in author_results.book_set.all():
    print(i)
© www.soinside.com 2019 - 2024. All rights reserved.