이 동작을 수행하는 템플릿 태그를 만들거나 템플릿에서 액세스 할 수있는 책 모델에 메서드를 추가 할 수 있습니다.
class Book(Model):
def other_books_users_read(self):
return Book.objects.filter(...)
{{ book.other_books_users_read }}
템플릿 태그 :
여기서 설명하는 가장 간단한 하나의 ... 그것은 사용자 정의 템플릿 태그가 어떻게 작동하는지 알아 내려고하지만, 본질적으로 코드가 될 것이다 당신의 책임
@register.assignment_tag
def get_other_books_users_read(book):
return Book.objects.filter(...) # logic here to get the books you need.
{% get_other_books_users_read book as other_books_users_read %}
{% for book in other_books_users_read %}
...
이제 컨텍스트에서 코드를 원한다면 한 줄의 코드 (및 점)가 너무 많이 사용되므로 컨텍스트에 컨텐트를 주입하는 미들웨어를 설정할 수 있습니다.
class MyMiddleware(object):
def process_template_response(self, request, response):
if 'book' in response.context_data:
response.context_data['other_books'] = Book.objects.filter(...)
return response
그러나 IMO 즉 말 그대로 템플릿에서 책 개체에 액세스 할 수 있기 때문에 템플릿 상황에 맞는 미들웨어를 사용하는 어리석은 방법이다
https://docs.djangoproject.com/en/dev/topics/http/middleware/?from=olddocs#process-template-response
.