python - Find by PK in Django model -


i'm working in django view author, first need pull authors. next need leverage model (book - included in view), , each author, want find books they've written active.

the book model has foreign key author (the author id or primary key)

i've got below ... it's not working , i'm stumped - thoughts?

def authors(request):    _vars = {}     authors = author.objects.all()      #loop through authors     author in authors.object_list:         books = book.objects.filter(author=author.pk).filter(is_active=true, author__is_active=true).order_by('-author__author_type__importance').exclude(author__is_active=false)         author.append(books)      _vars['authors'] = authors      return render(request, 'template.html', _vars) 

sorry: clarify - i'm unable run in debug mode, doing (stupidly) on live environment.

the server responds 500 error , i'm kinda blind why. line

        books = book.objects.filter(author=author.pk).filter(is_active=true, author__is_active=true).order_by('-author__author_type__importance').exclude(author__is_active=false) 

and suspicion primary key lookup. use exact same search in specific author , works - when try reference primary key in loop fails

what want return list of authors (id, name, age etc author model) along list of books (book id, book name etc)

i'd have object can go author.name (this authors name) or author.books.name (get name of book - it'd set of books i'd need iterate through - idea right?)

the template might like

{% author in authors %}     name: {{ author.name }}     age: {{ author.age }}     {% book in author.books %}         title: {{ book.title }}         published: {{ book.published }}     {% endfor %} {% endfor %} 

thanks

either use

books = book.objects.filter(author=author)filter(is_active=true, author__is_active=true).order_by('-author__author_type__importance').exclude(author__is_active=false) 

or use

books = book.objects.filter(author__id=author.id)filter(is_active=true, author__is_active=true).order_by('-author__author_type__importance').exclude(author__is_active=false) 

both work


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -