ขูดสภาพอากาศสำหรับมองภูเขา
Aug 20 2020
ฉันได้สร้างเว็บไซต์ใน Django ซึ่งฉันได้ลองสร้างแอปที่ซับซ้อนเป็นครั้งแรก เป็นแอปที่รวบรวมสภาพอากาศบนยอดเขาซึ่งเป็น 17 ฉันต้องการแสดงการคาดการณ์โดยละเอียดในเทมเพลตแยกต่างหากดังนั้นฉันจึงมี 17 มุมมองซึ่งเกือบจะเหมือนกัน
4 มุมมองเท่านั้น:
class KasprowyWierchForecastView(TemplateView):
"""
class for rendering view of detailed weather forecast for
Kasprowy Wierch peak
"""
template_name = 'mountain_base.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Peak'] = PeakForecast.objects.filter(
name_of_peak='Kasprowy').order_by('date')
print(context['Peak'])
return context
class KoscielecForecastView(TemplateView):
"""
class for rendering view of detailed weather forecast for
Koscielec peak
"""
template_name = 'mountain_base.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Peak'] = PeakForecast.objects.filter(
name_of_peak='Koscielec').order_by('date')
return context
class KrivanForecastView(TemplateView):
"""
class for rendering view of detailed weather forecast for Krivan peak
"""
template_name = 'mountain_base.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Peak'] = PeakForecast.objects.filter(
name_of_peak='Krivan').order_by('date')
return context
class MieguszowieckiForecastView(TemplateView):
"""
class for rendering view of detailed weather forecast for
Mieguszowiecki peak
"""
template_name = 'mountain_base.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Peak'] = PeakForecast.objects.filter(
name_of_peak='Mieguszowiecki').order_by('date')
return context
class MnichForecastView(TemplateView):
"""
class for rendering view of detailed weather forecast for
Mnich peak
"""
template_name = 'mountain_base.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Peak'] = PeakForecast.objects.filter(
name_of_peak='Mnich').order_by('date')
return context
เฉพาะชื่อของคลาสมุมมองและcontext['Peak']
แตกต่างกัน ส่วนที่เหลือของรหัสซ้ำซ้อน เนื่องจากประสบการณ์ของฉันขึ้นอยู่กับกระบวนการเรียนรู้ด้วยตนเองเท่านั้นฉันจึงไม่พบทางออกที่ดีในการแก้ไขหรือปรับโครงสร้าง
คำตอบ
2 fabrizzio_gz Aug 20 2020 at 09:34
ทางเลือกหนึ่งคือการแก้ไขTemplateView
คลาสของคุณเพื่อรวมชื่อของจุดสูงสุดเป็นแอตทริบิวต์อินสแตนซ์ (พูดpeak_name
) และทำให้get_context_data
เมธอดใช้ประโยชน์ได้:
class TemplateView():
# Class attributes
def __init__(self, peak_name):
# Instance attributes
# ...
self.peak_name = peak_name
# Class methods
# Modification of the get_context_data method
def get_context_data(self, **kwargs):
context['Peak'] = PeakForecast.objects.filter(
name_of_peak=self.peak_name).order_by('date') #<- Modification here
print(context['Peak'])
return context
จากนั้นคุณสามารถสร้างมุมมองสูงสุดของคุณเป็นอินสแตนซ์ของคลาสนั้น:
krivan_view = TemplateView('Krivan')
krivan_view.get_context_data(arg1='arg1', arg2='arg2')