django 在开发跨多个模型的多属性搜索时,我无法实现多对一的关系,

gcuhipw9  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(83)

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_结果.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  %}


我是做搜索app的,允许用户搜索书籍与他们的属性和作者。所以它是“多属性跨多个模型”。问题是我不能把一对多的关系搜索。多对多一个作品.我想检索由一个作者写的书.当我搜索图书,它显示,作者,ISBN,页.但当我搜索作者,不能得到书籍.

mmvthczy

mmvthczy1#

要通过主模型访问辅助模型:模型名称前缀和_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)

相关问题