spaces=Space.objects.all()
many to many 또는 one to many로 연결된 데이터 가지고 오기
views.py에서 print(dir(space))
입력해서 space객체가 쓸 수 있는 메소드 확인하기
<class명>_set
이용하여 many to many 또는 one to many로 연결된 데이터 가지고 오기
# 공간의 태그 가져오기
spaces = Space.objects.all()
for space in spaces:
print(space.spacetag_set.all())
for tag in space.spacetag_set.all():
print(tag.tag.name)
# 공간의 타입 가져오기
for i in spaces:
print(i.name) # 공간의 이름
for space_type in i.types.all(): #공간과 mtm로 연결된 타입을 모두 호출
print(space_type.name) #공간의 타입의 이름
python shell
에서 연습해서 데이터를 불러올 수 있으면 views.py에 코드를 작성할 차례!
many to many 또는 one to many로 연결된 데이터를 가지고 오기 위해서는 for문이 두 번 돌아야 함
이럴 경우 list comprehension 이용하여 코드작성하기
list comprehension
[(변수를 활용할 값) for (사용할 변수 이름) in (순회할 수 있는 값)]
# spaces/views.py
spaces=Space.objects.all()
data=[]
for space in spaces:
data.append(
{
"tag" = [tag.tag.name for tag in space.spacetag_set.all()]
"types" = [space_type.name for space_type in space.types.all()]
}
)
return JsonResponse({"data":data}, status = 201)
data
라는 빈 리스트를 선언하여 데이터 요소들을 append
하여 리스트에 추가하는 방법으로 작성한 코드를 list comprehension을 사용하여 코드를 줄일 수 있다.
# spaces/views.py
spaces=Space.objects.all()
data = [
{
"tag" = [tag.tag.name for tag in space.spacetag_set.all()]
"types" = [space_type.name for space_type in space.types.all()]
}
for space in spaces
]
return JsonResponse({"data":data}, status = 201)
aggregation 공식문서
django database abstraction API
사용하기 전에 반드시
from django.db.models import Max,Avg
import 할 것!
space와 one to many로 연결되어 있는 detailspace의 속성 "max_people"의 최대값을 구하기
<class명>.objects.all.aggregate(Max("속성"))
최대값 구하기
<class명>.objects.all.aggregate(Avg("속성"))
평균값 구하기
spaces.views.py
spaces = Space.objects.all()
results = [
{
"max_people" = space.detailspace_set.all().aggregate(Max("max_people"))["max_people__max"]
}
for space in spaces:
]
# ["max_people__max"] 프론트에 데이터 보내줄 때 조금더 깔끔하게?보내주기위해, 딕셔너리형태?