TIL33 - Actors & Movies usnig Django
Actors & Movies usnig Django
1.質問
2.コード
2-1. models.py
from django.db import models
# Create your models here.
class Movies(models.Model) :
title = models.CharField(max_length=50)
release_date = models.DateField()
running_time = models.IntegerField()
actors = models.ManyToManyField('Actors')
class Meta :
db_table = 'movies'
class Actors(models.Model) :
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
date_of_birth = models.DateField()
class Meta :
db_table = 'actors'
2-2. views.py
POSTは、条件が分離された後に2つのテーブルに接続するために条件文を作成する必要がある.
まず、単純入力のみのコード作成import json
from django.db.models.base import ModelBase
from django.http import JsonResponse
from django.views import View
from crud_movies.models import *
class ActorsView(View) :
def post(self, request) :
data = json.loads(request.body)
Actors.objects.create(
first_name = data['fn'],
last_name = data['ln'],
date_of_birth = data['birth'],
)
return JsonResponse({'create':'success'}, status=201)
def get(self, request) :
actors = Actors.objects.all()
result = []
for actor in actors :
movies = actor.movies_set.all()
mv_list = []
for movie in movies :
mv_list.append(
{
'title' : movie.title
}
)
result.append(
{
'first_name' : actor.first_name,
'last_name' : actor.last_name,
'movie' : mv_list
}
)
return JsonResponse({'result':result}, status=200)
class MoviesView(View) :
def post(self, request) :
data = json.loads(request.body)
Movies.objects.create(
title = data['title'],
release_date = data['r_date'],
running_time = data['r_time']
)
return JsonResponse({'create':'success'}, status=201)
def get(self, request) :
movies = Movies.objects.all()
result = []
for movie in movies :
actors = movie.actors.all()
actor_list=[]
for actor in actors :
actor_list.append(
{'name' : actor.last_name + ' ' + actor.first_name}
)
result.append(
{
'title' : movie.title,
'release_date' : movie.release_date,
'running_time' : movie.running_time,
'actors' : actor_list
}
)
return JsonResponse({'result':result}, status=200)
3.getクエリー結果
まず1つだけバインドされ、2つのクエリーセットを接続するために逆参照が使用されます.
4番での逆参照メソッドの作成
4.ManyToManyFieldを使用する理由
ManyToManyField()とForeginKey()の違いを比較します.
犬-飼い主とバンドというレベルを作りました.
名前は飼い主ですが、犬-人-バンド関係、犬-飼い主はFK、人-バンドはM 2 M
4-1. models.py
class Owners(models.Model) :
name = models.CharField(max_length=50)
email = models.EmailField(max_length=150, verbose_name='주인 이메일명')
age = models.IntegerField()
class Meta :
db_table = 'owners'
class Dogs(models.Model) :
owner = models.ForeignKey('Owners', on_delete=models.CASCADE)
name = models.CharField(max_length=50)
age = models.IntegerField()
class Meta :
db_table = 'dogs'
class Bands(models.Model) :
name = models.CharField(max_length=50)
members = models.ManyToManyField('Owners')
class Meta :
db_table = 'bands'
4-2. views.py
class BandsView(View) :
def post(self, request) :
data = json.loads(request.body)
bands = Bands.objects.create(
name = data['name']
)
return JsonResponse({'result':'good'},status=201)
class OwnersView(View) :
#주인이름/주인나이/강아지이름/강아지나이
def get(self, request) :
owners = Owners.objects.all()
result = []
for owner in owners :
dogs = owner.dogs_set.all()
dogs_list=[]
for dog in dogs :
dogs_list.append({
'dog_name' : dog.name,
'dog_age' : dog.age
})
result.append({
'owner_name' : owner.name,
'owner_age' : owner.age,
'dog_info' : dogs_list
})
return JsonResponse({'reulst' : result}, status=200)
def post(self, request) :
data = json.loads(request.body)
try :
ow = Owners.objects.create(
name = data['name'],
email = data['email'],
age = data['age']
)
ow.bands_set.add(data['b_id'])
return JsonResponse({'result' : 'good'}, status=201)
except AttributeError as message :
print(message)
class DogsView(View) :
#개이름, 나이, 주인
def get(self, request) :
dogs = Dogs.objects.all()
result = []
for dog in dogs :
result.append({
'dog_name' : dog.name,
'dog_age' : dog.age,
'owner_name' : Owners.objects.get(id=dog.owner_id).name
})
return JsonResponse({'result':result}, status=200)
def post(self, request) :
data = json.loads(request.body)
try :
Dogs.objects.create(
name = data['name'],
age = data['age'],
owner_id = data['owner_id']
)
return JsonResponse({'result':'good'}, status=201)
except ValueError as message :
print('오류메시지 : ', message)
まず,モデル構造が変化したのでmigrateを行った.
その結果,バンドの表とband membersというM 2 M関係が表を形成することを示した.
POST リクエストによりバンドにデータが生成された. try :
ow = Owners.objects.create(
name = data['name'],
email = data['email'],
age = data['age']
)
ow.bands_set.add(data['b_id'])
これは上のビューですpyの一部を取得し、ownerデータを生成するとき
生成されたオブジェクトを用いてバンドを逆参照し,データを中間テーブルに入れる.
これにより、テーブルにデータが作成されたことを確認できます.
中間表を通らずに、逆参照でデータを入れることができます.これが最大のメリットです.
また,データを逆順グループとしてどれだけ入れることができ,データを逆順グループとしてどれだけ読み込むことができるか.
OwnersとBandsはM 2 M関係であり,逆参照でデータを取得できる.
owという変数にid=12のオブジェクトを入力し、そのオブジェクトを小文字で参照するbandsとしてsetを付けます.
これにより、私のデータを参照することができます.
5.後期
自分でコードしてみましたが、習ったばかりの段階かもしれませんが、こんなに気持ちがいいですか?この考えはあまり説得力がない.
これからも慣れようと努力し続けます.
もちろん、逆参照方法は確かに革命である.
Reference
この問題について(TIL33 - Actors & Movies usnig Django), 我々は、より多くの情報をここで見つけました
https://velog.io/@kyleee/TIL33-Actors-Movies-usnig-Django
テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol
from django.db import models
# Create your models here.
class Movies(models.Model) :
title = models.CharField(max_length=50)
release_date = models.DateField()
running_time = models.IntegerField()
actors = models.ManyToManyField('Actors')
class Meta :
db_table = 'movies'
class Actors(models.Model) :
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
date_of_birth = models.DateField()
class Meta :
db_table = 'actors'
import json
from django.db.models.base import ModelBase
from django.http import JsonResponse
from django.views import View
from crud_movies.models import *
class ActorsView(View) :
def post(self, request) :
data = json.loads(request.body)
Actors.objects.create(
first_name = data['fn'],
last_name = data['ln'],
date_of_birth = data['birth'],
)
return JsonResponse({'create':'success'}, status=201)
def get(self, request) :
actors = Actors.objects.all()
result = []
for actor in actors :
movies = actor.movies_set.all()
mv_list = []
for movie in movies :
mv_list.append(
{
'title' : movie.title
}
)
result.append(
{
'first_name' : actor.first_name,
'last_name' : actor.last_name,
'movie' : mv_list
}
)
return JsonResponse({'result':result}, status=200)
class MoviesView(View) :
def post(self, request) :
data = json.loads(request.body)
Movies.objects.create(
title = data['title'],
release_date = data['r_date'],
running_time = data['r_time']
)
return JsonResponse({'create':'success'}, status=201)
def get(self, request) :
movies = Movies.objects.all()
result = []
for movie in movies :
actors = movie.actors.all()
actor_list=[]
for actor in actors :
actor_list.append(
{'name' : actor.last_name + ' ' + actor.first_name}
)
result.append(
{
'title' : movie.title,
'release_date' : movie.release_date,
'running_time' : movie.running_time,
'actors' : actor_list
}
)
return JsonResponse({'result':result}, status=200)
class Owners(models.Model) :
name = models.CharField(max_length=50)
email = models.EmailField(max_length=150, verbose_name='주인 이메일명')
age = models.IntegerField()
class Meta :
db_table = 'owners'
class Dogs(models.Model) :
owner = models.ForeignKey('Owners', on_delete=models.CASCADE)
name = models.CharField(max_length=50)
age = models.IntegerField()
class Meta :
db_table = 'dogs'
class Bands(models.Model) :
name = models.CharField(max_length=50)
members = models.ManyToManyField('Owners')
class Meta :
db_table = 'bands'
class BandsView(View) :
def post(self, request) :
data = json.loads(request.body)
bands = Bands.objects.create(
name = data['name']
)
return JsonResponse({'result':'good'},status=201)
class OwnersView(View) :
#주인이름/주인나이/강아지이름/강아지나이
def get(self, request) :
owners = Owners.objects.all()
result = []
for owner in owners :
dogs = owner.dogs_set.all()
dogs_list=[]
for dog in dogs :
dogs_list.append({
'dog_name' : dog.name,
'dog_age' : dog.age
})
result.append({
'owner_name' : owner.name,
'owner_age' : owner.age,
'dog_info' : dogs_list
})
return JsonResponse({'reulst' : result}, status=200)
def post(self, request) :
data = json.loads(request.body)
try :
ow = Owners.objects.create(
name = data['name'],
email = data['email'],
age = data['age']
)
ow.bands_set.add(data['b_id'])
return JsonResponse({'result' : 'good'}, status=201)
except AttributeError as message :
print(message)
class DogsView(View) :
#개이름, 나이, 주인
def get(self, request) :
dogs = Dogs.objects.all()
result = []
for dog in dogs :
result.append({
'dog_name' : dog.name,
'dog_age' : dog.age,
'owner_name' : Owners.objects.get(id=dog.owner_id).name
})
return JsonResponse({'result':result}, status=200)
def post(self, request) :
data = json.loads(request.body)
try :
Dogs.objects.create(
name = data['name'],
age = data['age'],
owner_id = data['owner_id']
)
return JsonResponse({'result':'good'}, status=201)
except ValueError as message :
print('오류메시지 : ', message)
try :
ow = Owners.objects.create(
name = data['name'],
email = data['email'],
age = data['age']
)
ow.bands_set.add(data['b_id'])
Reference
この問題について(TIL33 - Actors & Movies usnig Django), 我々は、より多くの情報をここで見つけました https://velog.io/@kyleee/TIL33-Actors-Movies-usnig-Djangoテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol