Những hai đoạn mã giống hệt nhau tại blush đầu tiên:Sử dụng phương thức get_queryset() hoặc đặt biến truy vấn?
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_poll_list'
queryset = Poll.active.order_by('-pub_date')[:5]
và
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_poll_list'
def get_queryset(self):
return Poll.active.order_by('-pub_date')[:5]
Có sự khác biệt giữa chúng? Và nếu đó là:
Cách tiếp cận nào tốt hơn? Hoặc khi đặt biến số queryset
tốt hơn là ghi đè phương thức get_queryset
? Và ngược lại.
bạn cũng có thể viết trong 'get_queryset'' self.model.objects.filter (...) '. Trong trường hợp kế thừa danh sách riêng, bạn nên nhớ rằng người ta nên tham khảo 'siêu (YourListViewExtendingSomeOtherLV, self) .get_queryset(). Filter (...)' – andi