[Django] C.R.U.D - Many to Many relation using ForeignKey

Hailey Park·2021년 11월 16일
0

Django

목록 보기
5/10
post-thumbnail

Q1 - POST

POST

각 기능을 서로 다른 클래스로 구현해주세요.
1. 신규 주인 등록
2. 강아지 등록 (주인정보 필요)
위 기능을 구현 후 직접 httpie 를 활용하여 주인 2명의 정보와 각 주인 당 2~3마리의 강아지 정보를 데이터베이스에 저장해주세요.

Q2 - GET

GET

각 기능을 서로 다른 클래스로 구현해주세요.
1. 주인 리스트
- 이름, 이메일, 나이 포함
2. 강아지 리스트
- 이름, 나이, 주인 이름 포함
3. 주인 리스트 (1번 코드에 추가)
- 이름, 나이 포함, 키우는 강아지 리스트 (이름, 나이 포함)

@ Models.py

from django.db import models

# Create your models here.

class Owner(models.Model):
	name = models.CharField(max_length=20)
	email = models.EmailField(max_length=200)
	age = models.IntegerField()

	class Meta:
		db_table = 'owners'


class Pet(models.Model):
	name = models.CharField(max_length=20)
	age = models.IntegerField()
	owner = models.ForeignKey('Owner', on_delete=models.CASCADE)

	class Meta:
		db_table = 'pets'

@ View.py

from django.shortcuts import render

# Create your views here.

import json

from django.http  import JsonResponse
from django.views import View

from owners.models import Owner, Pet


class OwnerView(View):
    def post(self, request):
        data = json.loads(request.body)
        Owner.objects.create(
            name  = data['owner'],
            age   = data['age'],
            email = data['email']
            )
        return JsonResponse({'MESSAGE' : 'CREATED'}, status=201)
    def get(self, request):
        owners = Owner.objects.all()
        results = []
        for owner in owners:
            results.append(
            {
            	"name"     : owner.name,
                "age"      : owner.age,
                "email"    : owner.email,
                     
                    	}
                )
        return JsonResponse({'results':results}, status =200)

class PetView(View):
    def post(self, request):
        data = json.loads(request.body)
        owner = Owner.objects.get(name = data['owner'])
        Pet.objects.create(
				name = data['pet'],
    			age  = data['age'],
				owner = owner
				)
        return JsonResponse({'MESSAGE' : 'CREATED'}, status=201)
    
    def get(self, request):
        pets = Pet.objects.all()
        results = []
        for pet in pets:
            results.append(
                {
                    "name"  : pet.name,
                    "age"   : pet.age,
                    "owner" : pet.owner.name
				}
			)
        return JsonResponse({'results':results}, status = 200)

class OwnerpetView(View):
    def get(self,request):
        owners = Owner.objects.all()
        results = []
        for owner in owners:
            pet_list = []
            pets = owner.pet_set.all()
            for pet in pets:
                pet_list.append(
                    {
                        "pet_name" : pet.name,
                        "pet_age"  : pet.age,
					}
				)
            results.append(
                {
                    "name"     : owner.name,
                    "age"      : owner.age,
                    "pet_list" : pet_list,
     
				}
			)
            
        return JsonResponse({'results':results}, status = 200)

@ urls.py



from django.urls import path

from owners.views  import OwnerView, PetView, OwnerpetView

urlpatterns = [
    path('owner',OwnerView.as_view()),
    path('pet',PetView.as_view()),
    path('ownerpet',OwnerpetView.as_view()),

]

@ main urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('owners/', include('owners.urls')),

]

Comparision between the codes

The comparision between the code when we want to get only one data and the code when we want to get all the data

  • When we want to get only one data, views.py is as below

[The result]

  • When we want to get all the data, views.py is as below

[The result]

profile
I'm a deeply superficial person.

0개의 댓글