[Answered ]-How to Call Two Fields From One Model in Django View

1👍

First of all

book = get_object_or_404 (Book, book_slug = book_slug)

this is a get method, which returns a single instance of book if found (not a Queryset)

Then you are repeating the same thing, and in my opinion this piece of code can be discarded since it’s a duplicate of the row above

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

Then in the template you don’t have to cicle on book: that’s a single object not an enumerable – queryset, so you should write

<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>

About your second query, based on your example data you cannot extract data with a filter, but have to process in this way:

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

0👍

Insisted of using filter(book_slug = book_slug) use __icontains with Q object (use the each word in book_slug inorder to get maximum similar entries).
for example : –

  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()

if you wish to eliminate explicit loop like above you can use operator to do that.

import operator

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

0👍

Try obtain list ahuthor book by first query and in second query filter all books with same authors

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

If you want exclude book from simiar books

   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)
 

Leave a comment