Skip to content

Commit

Permalink
Merge branch 'feature/View'
Browse files Browse the repository at this point in the history
  • Loading branch information
srlee056 committed Nov 10, 2023
2 parents 0cacc22 + 55c39e5 commit 28343a7
Show file tree
Hide file tree
Showing 7 changed files with 154 additions and 15,419 deletions.
58 changes: 36 additions & 22 deletions map_visual/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
import folium
import pandas as pd
import geopandas

sido_coordinate = {
"서울특별시": [37.5311, 126.9814],
Expand All @@ -25,29 +26,33 @@

def SidoMap(sido_data):
sido_path = "map_visual/geojson/si_do/HangJeongSiDo_ver20230701.json"
sido_geo = json.load(open(sido_path, encoding="utf-8"))
# sido_geo = json.load(open(sido_path, encoding="utf-8"))
sido_geo = geopandas.read_file(sido_path)
data = pd.DataFrame(sido_data)
result = pd.merge(sido_geo, data, on="sidonm")

sido_map = folium.Map(location=[37.541, 126.986], zoom_start=7)
data = pd.DataFrame(sido_data)
print(data)

folium.Choropleth(
sido_geo,
data=data,
columns=["sido_nm", "trading_volume"],
columns=["sidonm", "trading_volume"],
key_on="feature.properties.sidonm",
name="sido-map",
).add_to(sido_map)
# print(sido_data)

folium.GeoJson(
name="sido_info",
data=sido_geo,
data=result,
# click
# popup=folium.GeoJsonPopup(
# fields=["sidonm", "sido_cd"], aliases=["시이름", "코드번호"]
# ),
tooltip=folium.GeoJsonTooltip(
fields=["sidonm"], aliases=["시이름"], style=("font-size : 15px")
fields=["sidonm", "trading_volume"],
aliases=["지역이름", "거래량"],
style=("font-size : 15px"),
),
).add_to(sido_map)

Expand All @@ -57,11 +62,11 @@ def SidoMap(sido_data):

def SigugunMap(sido_name, sigugun_data):
sigugun_path = f"map_visual/geojson/si_gu_gun/{sido_name}.json"
sigugun_geo = json.load(open(sigugun_path, encoding="utf-8"))

data_csv = "map_visual/Total_People_2018.csv"
# data = pd.read_csv(data_csv, encoding="euc-kr")
# sigugun_geo = json.load(open(sigugun_path, encoding="utf-8"))
sigugun_geo = geopandas.read_file(sigugun_path)
data = pd.DataFrame(sigugun_data)
result = pd.merge(sigugun_geo, data, on="sgg_nm")

sigugun_map = folium.Map(
location=[sido_coordinate[sido_name][0], sido_coordinate[sido_name][1]],
zoom_start=11,
Expand All @@ -72,21 +77,23 @@ def SigugunMap(sido_name, sigugun_data):
name="sigugun-map",
data=data,
# columns=["Code", "Population"],
columns=["gugun_nm", "trading_volume"],
columns=["sgg_nm", "trading_volume"],
key_on="feature.properties.sgg_nm",
fill_color="OrRd", # 시각화할 색상
fill_opacity=0.7, # 색 투명도
line_opacity=0.2, # 경계선 투명도
legend_name="2018년 인구수", # 색상 범주 이름
# legend_name="2018년 인구수", # 색상 범주 이름
).add_to(sigugun_map)

folium.GeoJson(
data=sigugun_geo,
data=result,
name="sigugun_info",
# click
popup=folium.GeoJsonPopup(fields=["sgg_nm", "sgg_cd"], aliases=["구이름", "코드번호"]),
# popup=folium.GeoJsonPopup(
# fields=["sgg_nm", "trading_volume"], aliases=["지역이름", "거래량"]
# ),
tooltip=folium.GeoJsonTooltip(
fields=["sido_nm", "sido_cd"], aliases=["시이름", "코드번호"]
fields=["sgg_nm", "trading_volume"], aliases=["지역 이름", "거래량"]
),
).add_to(sigugun_map)

Expand All @@ -98,13 +105,20 @@ def SigugunMap(sido_name, sigugun_data):


def DongMap(sido_name, sigugun_name, dong_data):
sigugun_name = sigugun_name.replace(" ", "")
dong_path = f"map_visual/geojson/dong/{sido_name}/{sigugun_name}.json"
dong_geo = json.load(open(dong_path, encoding="utf-8"))
# dong_geo = json.load(open(dong_path, encoding="utf-8"))
dong_geo = geopandas.read_file(dong_path)
data = pd.DataFrame(dong_data)
data["adm_nm"] = sido_name + " " + sigugun_name + " " + data["dong_nm"]

result = pd.merge(dong_geo, data, on="adm_nm")

dong_map = folium.Map(
location=[sido_coordinate[sido_name][0], sido_coordinate[sido_name][1]],
zoom_start=11,
)

dong_boundary = folium.Choropleth(
dong_geo,
data=data,
Expand All @@ -115,15 +129,15 @@ def DongMap(sido_name, sigugun_name, dong_data):
).add_to(dong_map)

folium.GeoJson(
data=dong_geo,
data=result,
name="dong_info",
# click
popup=folium.GeoJsonPopup(
fields=["adm_nm", "adm_cd2"], aliases=["지역명", "코드번호"]
),
# popup=folium.GeoJsonPopup(
# fields=["adm_nm", "adm_cd2"], aliases=["지역명", "코드번호"]
# ),
tooltip=folium.GeoJsonTooltip(
fields=["sidonm", "sido", "sggnm", "sgg"],
aliases=["시이름", "코드번호", "구이름", "코드번호"],
fields=["adm_nm", "trading_volume", "average_price"],
aliases=["지역이름", "거래량", "평균 매매가"],
),
).add_to(dong_map)

Expand Down
8 changes: 4 additions & 4 deletions trades/templates/trades/detail.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{% if region %}
<h1>{{region.dong_name}}의 집값 추이는?</h1>

<ul>
{% if realestates %}
<li>
<p>trading volume : {{trading_volume}}</p>
<p>average price : {{average_price}}</p>
Expand All @@ -11,7 +11,7 @@ <h1>{{region.dong_name}}의 집값 추이는?</h1>
<p>{{t}}</p>
{% endfor %}
</li>
{% else %}
<p>no real estaes</p>
{% endif %}
</ul>
{% else %}
<p>no real estaes</p>
{% endif %}
2 changes: 1 addition & 1 deletion trades/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@

urlpatterns = [
path("", views.index, name="index"),
path("detail/<int:region_id>/", views.detail, name="detail"),
path("detail/", views.detail, name="detail"),
]
155 changes: 64 additions & 91 deletions trades/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,50 +11,69 @@
# Create your views here.
def index(request):
# regions = Region.objects.all()
raw_data = {}
raw_data = {
"trading_volume": [],
"average_price": [],
"highest_price": [],
"lowest_price": [],
}
context = {}

if "gugun_nm" in request.GET:
sido_nm = request.GET["sido_nm"]
gugun_nm = request.GET["gugun_nm"]
dong_of_gugun = local_name_3[f"{sido_nm} {gugun_nm}"]
context = {"regions": dong_of_gugun, "sido": sido_nm, "gugun": gugun_nm}
sub_regions = local_name_3[f"{sido_nm} {gugun_nm}"]
context["sido"] = sido_nm
context["gugun"] = gugun_nm

trades = _get_gugun_trades(2023, 9, sido_nm, gugun_nm)
raw_data["adm_nm"] = []
raw_data["trading_volume"] = []
for dong_nm in dong_of_gugun:
raw_data["adm_nm"].append(f"{sido_nm} {gugun_nm} {dong_nm}")
raw_data["trading_volume"].append(
trades.filter(real_estate__region__dong_name=dong_nm).count()
raw_data["dong_nm"] = []
for dong_nm in sub_regions:
raw_data["dong_nm"].append(dong_nm)
_context = _get_context(
trades.filter(real_estate__region__dong_name=dong_nm)
)
raw_data = {
key: value + [_context[key]] if key in _context else value
for key, value in raw_data.items()
}
context["map"] = DongMap(sido_nm, gugun_nm, raw_data)
elif "sido_nm" in request.GET:
sido_nm = request.GET["sido_nm"] # url query에서 시/도 명 가져와서 저장
gugun_of_sido = local_name_2[sido_nm]
context = {"regions": gugun_of_sido, "sido": sido_nm} # context로 넘김
sido_nm = request.GET["sido_nm"]
sub_regions = local_name_2[sido_nm]
context["sido"] = sido_nm

trades = _get_sido_trades(2023, 9, sido_nm)
raw_data["gugun_nm"] = []
raw_data["trading_volume"] = []
for gugun_nm in gugun_of_sido:
raw_data["gugun_nm"].append(gugun_nm)
raw_data["trading_volume"].append(
trades.filter(real_estate__region__gu_gun_name=gugun_nm).count()
raw_data["sgg_nm"] = []
for gugun_nm in sub_regions:
raw_data["sgg_nm"].append(gugun_nm.replace(" ", ""))
_context = _get_context(
trades.filter(real_estate__region__gu_gun_name=gugun_nm)
)
raw_data = {
key: value + [_context[key]] if key in _context else value
for key, value in raw_data.items()
}
context["map"] = SigugunMap(sido_nm, raw_data)

else:
region_all = local_name_1["전국"]
context = {"regions": region_all}
sub_regions = local_name_1["전국"]

trades = _get_all_trades(2023, 9)
raw_data["sido_nm"] = []
raw_data["trading_volume"] = []
for sido_nm in region_all:
raw_data["sido_nm"].append(sido_nm)
raw_data["trading_volume"].append(
trades.filter(real_estate__region__si_do_name=sido_nm).count()
raw_data["sidonm"] = []
for sido_nm in sub_regions:
raw_data["sidonm"].append(sido_nm)
_context = _get_context(
trades.filter(real_estate__region__si_do_name=sido_nm)
)
raw_data = {
key: value + [_context[key]] if key in _context else value
for key, value in raw_data.items()
}
context["map"] = SidoMap(raw_data)

# print(raw_data)
context.update(_get_context(trades))

context["regions"] = sub_regions
return render(request, "trades/index.html", context)


Expand Down Expand Up @@ -97,7 +116,6 @@ def _get_dong_trades(cur_year, cur_month, sido_nm, gugun_nm, dong_nm):


def _get_context(trades):
context = {}
average_price, highest_price, lowest_price = 0, 0, 0
trading_volume = trades.count()
total_price = trades.aggregate(total_price=models.Sum("trade_price"))["total_price"]
Expand All @@ -116,72 +134,27 @@ def _get_context(trades):

return {
"trading_volume": trading_volume,
"average_price": average_price,
"average_price": int(average_price),
"highest_price": highest_price,
"lowest_price": lowest_price,
}


def detail(request, region_id):
region = get_object_or_404(Region, pk=region_id)
si_do_name = region.si_do_name
gu_gun_name = region.gu_gun_name
dong_name = region.dong_name

realestates = region.realestates.all()
# 현재 날짜를 기준으로 이번 달 거래 objects를 가져옴
current_year = datetime(2023, 9, 1).year
current_month = datetime(2023, 9, 1).month
this_month_trading = RealEstateTrade.objects.filter(
trade_year=current_year,
trade_month=current_month,
real_estate__region__pk=region_id,
)
trading_volume = this_month_trading.count() # 이번달 거래량
print(
f"{current_year} - {current_month} trading volume: {trading_volume} trades"
) # test code
# 평균값 구하는 과정
total_price = this_month_trading.aggregate(total_price=models.Sum("trade_price"))[
"total_price"
]
if trading_volume > 0:
average_price = total_price / trading_volume
else:
average_price = 0
print(
f"{current_year} - {current_month} average trading price: {average_price}"
) # test code

# 가장 높은 거래 가격을 가진 주택을 찾는 코드
highest_price_trade = this_month_trading.order_by("-trade_price").first()
if highest_price_trade is not None:
highest_price = highest_price_trade.trade_price
print(
f"The highest priced housing in {si_do_name} {gu_gun_name} {dong_name}: {highest_price_trade.real_estate.estate_name}, Price: {highest_price}"
)
else:
highest_price = 0
print(f"No trade information found")

# 가장 낮은 거래 가격을 가진 주택을 찾는 코드
lowest_price_trade = this_month_trading.order_by("trade_price").first()
if lowest_price_trade:
lowest_price = lowest_price_trade.trade_price
print(
f"The lowest priced housing in {si_do_name} {gu_gun_name} {dong_name}: {lowest_price_trade.real_estate.estate_name}, Price: {lowest_price}"
)
def detail(request):
names = request.GET["dong_nm"].strip().split("-")
sido_nm = names[0]
gugun_nm = names[1]
dong_nm = names[2]
region = Region.objects.filter(
si_do_name=sido_nm, gu_gun_name=gugun_nm, dong_name=dong_nm
).first()
if region:
# realestates = region.realestates
trades = _get_dong_trades(2023, 9, sido_nm, gugun_nm, dong_nm)
context = _get_context(trades)
context["region"] = region
# context["realestates"] = realestates
context["trades"] = trades
else:
lowest_price = 0
print(f"No trade information found")

context = {
"trading_volume": trading_volume,
"average_price": average_price,
"region": region,
"lowest_price": lowest_price,
"highest_price": highest_price,
"realestates": realestates,
"trades": this_month_trading,
}
context = {}
return render(request, "trades/detail.html", context)
3 changes: 2 additions & 1 deletion utils/local_name.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,8 @@
"익산시",
"정읍시",
"남원시",
"김제시" "완주군",
"김제시",
"완주군",
"진안군",
"무주군",
"장수군",
Expand Down
Loading

0 comments on commit 28343a7

Please sign in to comment.