각 기능을 서로 다른 클래스로 구현해주세요.
위 기능을 구현 후 직접 httpie 를 활용하여 주인 2명의 정보와 각 주인 당 2~3마리의 강아지 정보를 데이터베이스에 저장해주세요.
각 기능을 서로 다른 클래스로 구현해주세요.
from django.db import models
class Owner(models.Model):
name = models.CharField(max_length=45, null=True, blank=True)
email = models.CharField(max_length=45, null=True, blank=True)
age = models.PositiveSmallIntegerField(null=True, blank=True)
class Meta:
db_table = 'owners'
class Dog(models.Model):
owner = models.ForeignKey('Owner', on_delete=models.CASCADE)
name = models.CharField(max_length=45, null=True, blank=True)
age = models.PositiveSmallIntegerField(null=True, blank=True)
class Meta:
db_table = 'dogs'
from django.urls import path, include
urlpatterns = [
path('owners', include('owners.urls'))
]
from django.urls import path
from .views import OwnerView, DogView
urlpatterns = [
path('/owner', OwnerView.as_view()),
path('/dog', DogView.as_view())
]
path('', )
만 넣고 view.py 작성후 path값을 다시 urls.py에 넣어주었다.as_view
: http요청이 해당 클래스로 요청이 들어올 때, get, post, update, delete인지 등에 맞게 알아서 처리해줌.import json
from django.views import View
from django.http import JsonResponse
from .models import Owner, Dog
class OwnerView(View):
def post(self, request):
data = json.loads(request.body)
Owner.objects.create(
name = data['name'],
email = data['email'],
age = data['age']
)
return JsonResponse({'message':'SUCCESS'}, status=201)
request
: http의 요청에 대한 모든 정보를 담고 있는 객체. body, status, query string 등을 가져옴class DogView(View):
def post(self, request):
data = json.loads(request.body)
owner = Owner.objects.get(email=data['owner']) # owner
Dog.objects.create(
name = data['name'],
age = data['age'],
owner = owner
)
return JsonResponse({'message':'SUCCESS'}, status=201)
GET은 쿼리셋으로 넘겨줘야 되기 때문에, Json이 이해할 수 있도록 dictionary형식으로 넘겨야한다.
class OwnerView(View):
def get(self, request):
owners = Owner.objects.all()
result = []
for owner in owners:
dogs = owner.dog_set.all() #Owner로 Dog를 참조
dogs_list = []
for dog in dogs:
dog_info = {
'name' : dog.name,
'age' : dog.age
}
dogs_list.append(dog_info)
owner_info = {
'email' : owner.email,
'name' : owner.name,
'age' : owner.age,
'dogs' : dogs_list
}
result.append(owner_info)
return JsonResponse({'result': result}, status=200)
def get(self, request):
dogs = Dog.objects.all()
result = []
for dog in dogs:
dog_info = {
'owner' : dog.owner.name, #foreignkey를 사용했으니, dog의 owner name을 불러옴
'name' : dog.name,
'age' : dog.age,
}
result.append(dog_info)
return JsonResponse({'result': result}, status=200)
my_list = [1, 2, 3, 4, 5]
b = [num for num in my_list]
print(b)
#출력
[1, 2, 3, 4, 5]
my_list2 [{'a': 1, 'b': 2}, {'a,': 3, 'b' : 4}]
b = [num['a'] for num in my_list2]
print(b)
# 출력
[1, 3]
class OwnerView(View):
def get(self, request):
owners = Owner.objects.all()
result = []
for owner in owners:
dogs = owner.dog_set.all()
dogs_list = [{
'name': dog.name,
'age' : dog.age
} for dog in dogs]
owner_info = {
'email' : owner.email,
'name' : owner.name,
'age' : owner.age,
'dogs' : dogs_list
}
result.append(owner_info)
return JsonResponse({'result': result}, status=200)