Django:ManyToMany関係

2941 ワード

ManyToMany


1つのモデルは別のモデルと異なる関係を持つことができ、逆も同様である.
映画と俳優の関係でお見せしましょう
models.py

  1 from django.db import models
  2 from django.db.models.deletion import CASCADE
  3
  4 # Create your models here.
  5
  6 class Actor(models.Model):
  7     first_name = models.CharField(max_length=45)
  8     last_name = models.CharField(max_length=45)
  9     date_of_birth = models.DateField(auto_now=False, null=Tr    ue)
 10     movies = models.ManyToManyField('Movie', through='Actor_    Movie')
 11     class Meta:
 12         db_table="actors"
 13
 14
 15
 16 class Movie(models.Model):
 17     title = models.CharField(max_length=45)
 18     release_date = models.DateField(auto_now=False, null=Tru    e)
 19     running_time = models.TimeField(auto_now=False, null=Tru    e)
 20     class Meta:
 21         db_table="movies"
 22
 23 class Actor_Movie(models.Model):
 24     actors = models.ForeignKey('Actor', on_delete=models.CAS    CADE)
 25     movies = models.ForeignKey('Movie', on_delete=models.CAS    CADE)
 26     class Meta:
 27         db_table="actor_movie"
上記モデリングでは、shellで参照と逆参照を中間テーブルに入れて確認します.
# a에 하정우 정보를 담고
a = Actor.objects.get(id=1)

#b에는 암살 
b = Movie.objects.get(id=1)

# manytomany 로 연결되어 있는 movies를 이용해 정참조로 값을 넣어준다

# middle table에  값을 넣기
a.movies.add(b)

#역참조
b.actor_set.add(a)

正の参照


すべての俳優を招待した映画作品
 10 class MoviesView(View):
 11     def get(self,request):
 12         ac = Actor.objects.all()
 13         results=[]
 14         for a in ac:
 15             results.append(
 16                 {
 17                     "first_name" : a.first_name,
 18                     "movies" : [i.title for i in a.movies.all()],
 19                 }
 20             )
 21         return JsonResponse({"result":results}, status = 201)

逆参照


映画俳優
 24 class ActorView(View):
 25     def get(self,request):
 26         m = Movie.objects.all()
 27         results=[]
 28         for a in m:
 29             results.append(
 30                 {
 31                     "title" : a.title,
 32                     "release_date" : a.release_date,
 33                     "running_time" : a.running_time,
 34                     "actor" : [i.last_name for i in a.actor_set.all()],
 35                 }
 36             )
 37         return JsonResponse({"result":results}, status = 201)