如何在Django视图中从一个模型调用两个字段

oxcyiej7  于 2023-01-31  发布在  Go
关注(0)|答案(3)|浏览(169)

我现在有一个模型,我想在同一个视图中显示它的两个字段。然后在详细信息模板中显示它们。但结果返回空in template。最好的方法是什么?
我的模特:

class Book(models.Model): 
   class Meta :
       verbose_name_plural = 'Books'
   category = models.ForeignKey(Categorie,on_delete=models.CASCADE,null=True, 
   related_name="apps")
   book_slug = models.SlugField(blank=True,allow_unicode=True,editable=True)
   book_title = models.CharField(max_length=50 , null=True)
   book_picture = models.ImageField(upload_to='imgs' , null=True)
   book_description = RichTextUploadingField(null=True,blank=True)
   book_size = models.CharField(max_length=20 , null=True)
   book_created_at = models.DateField(auto_now_add=True)
   book_updated_at = models.DateField(auto_now=True)
   book_auther = models.CharField(max_length=100 , null=True)

我的看法:

def book_details(requset ,book_slug):    
     book = get_object_or_404 (Book, book_slug = book_slug)
     try :
         book = Book.objects.filter(book_slug = book_slug)
     except :
         raise Http404
     similar_books = Book.objects.filter(book_auther = book_slug)  ------ >>> Here is my query

     context ={
        'book' :book,
        'similar_books':similar_books,
      }
  return render( requset,'book.html',context)

我的模板:

<div class="row">
{% for b in book %}
        <div>
            <img src="{{ b.book_picture.url }}" class="Rounded circle Image" height="150" 
            width="150" alt="">
            <a href="{{b.get_absolute_url}}">{{b.book_title}}</a>
        </div>
{% endfor %}
</div>

<div class="row">
{% for sb in similar_books%}
        <div>
            <img src="{{ sb.book_picture.url }}" class="Rounded circle Image" height="150" 
            width="150" alt="">
            <a href="{{sb.get_absolute_url}}">{{sb.book_title}}</a>
        </div>
{% endfor %}
</div>
hpxqektj

hpxqektj1#

首先

book = get_object_or_404 (Book, book_slug = book_slug)

这是一个get方法,如果找到book的单个示例(不是Queryset),则返回该示例
那么您就是在重复同样的事情,在我看来,这段代码可以丢弃,因为它是上面一行的重复

try :
     book = Book.objects.filter(book_slug = book_slug)
 except :
     raise Http404

然后在模板中,您不必循环使用book:这是一个单独对象,而不是一个可枚举的查询集,因此您应该编写

<div class="row">
        <div>
            <img src="{{ book.book_picture.url }}" class="Rounded circle Image" height="150" 
            width="150" alt="">
            <a href="{{book.get_absolute_url}}">{{book.book_title}}</a>
        </div>
</div>

关于第二个查询,根据示例数据,您不能使用筛选器提取数据,而必须以以下方式处理:

similar_books = []
for sb in Book.objects.all():
   if sb.book_author in book_slug:
      similar_books.append(sb)
puruo6ea

puruo6ea2#

坚持使用过滤器(book_slug = book_slug)使用__图标与Q对象(使用book_slug中的每个单词以获得最大相似条目)。例如:-

slugs = book_slug.split() # which will give list of slugs

  condition = Q(book_slug__icontains=slugs[0])
  for slug in slugs[1:]:
     condition &= Q(book_slug__icontains=slug)
  Book.objects.filter(condition).all()

如果您希望消除如上所述显式循环,可以使用operator来实现。

import operator

slug_conditions = reduce(operator.and_, [Q(book_slug__icontains=slug) for slug in book_slug])
queryset = Profile.objects.filter(slug_conditions).all()
mlmc2os5

mlmc2os53#

尝试通过第一个查询获取一本书的列表,并在第二个查询中筛选所有作者相同的书

book = Book.objects.filter(book_slug=book_slug)
   authors = book.values_list('book_auther').distinct()
   similar_books = Book.objects.filter(book_auther__in=authors)

如果要从类似帐簿中排除帐簿

book = Book.objects.filter(book_slug=book_slug)
   authors = book.values_list('book_auther').distinct()
   book_ids = book.values_list('id', flat=True)
   similar_books = Book.objects.filter(book_auther__in=authors).exclude('id__in'=book_ids)

相关问题