M:N project (DRF)

31904 ワード

🌤️ DRF M:N relation


1.モデリング


$ python -m venv venv
$ source venv/Scripts/activate    >> 안되면 ctrl+shift+p 로 잡아주기
$ pip install django django_extensions djangorestframework

$ django-admin startproject live08
$ python manage.py startapp jukebox  
>> settings 
'jukebox'
'django_extensions'
'rest_framework'
>> models.py
class Artist(models.Model):
	name = models.CharField(max_length=100)
  debut = models.DateField()
  def __str__(self):
		return f'{self.pk}:{self.name}'
------------------------------------------------------------------
class Album(models.Model):
	name = models.CharField(max_length=100)
	artists = models.ManytoManyField(Artist,related_name='albums')

	def __str__(self):
		return f'{self.pk}:{self.name}'
------------------------------------------------------------------
class Track(models.Model):
	album = models.Foreignkey(Album, on_delete=models.CASCADE)
  artists = models.ManytoManyField(Artist,related_name='tracks')
	title = models.CharField(max_length=100)
	lyric = models.TextField()    **>> 비어도 괜찮게**
  click = models.PositiveIntegerField(default=0)  **>> 조회수**(기본값=0)

	****def __str__(self):
		return f'{self.pk}:{self.name}'
****
>> admin.py
from django.contrib import admin
from .models import Artist, Album, Track

admin.site.register(Artist); admin.site.register(Album); admin.site.register(Track)

$ python manage.py createsuperuser
>> live08/urls.py
path('api/v1/',include('jukebox.urls'))

>> jukebox/urls.py
path('artists/',views.artist_list_or_create),
path('artists/<int:artist_pk>/',views.artist_detail_or_update_or_delete),

path('albums/',views.album_list_or_create),
path('albums/<int:album_pk>/',views.album_detail_or_update_or_delete),

path('albums/<int:album_pk>/tracks/<int:track_pk>/',views.track_detail_or_update_or_delete),
>> jukebox/serializers/ (album.py, artist.py, track.py)  - 나눈다
from rest_framework import serializers
from ..models import Artist

class ArtistListSerializer(serializers.ModelSerializer):
	class Meta:
		model = Artist
		fields = ('id','name')

class ArtistSerializer(serializers.ModelSerializer):

	class TrackSerializer(serializers.ModelSerializer):
		class Meta:
			model = Track
			fields = ('id','title')

	class AlbumSerializer(serailizers.ModelSerializer):
		class Meta:
			model = Album
			fields = ('id','title')

	name = serializers.CharField(min_length=1,max_length=100)
	tracks = TrackSerializer(many=True, read_only=True)
	albums = AlbumSerailizer(many=True, read_only=True)  **비어도 괜찮**
	album_count = serializers.IntegerField(source='albums.count',read_only=True)
	

	class Meta:
		model = Artist
		fields = '__all__' >> ('id','name','debut','albums','tracks','album_count') >>
-----------------------------------------------------------------------------------

class AlbumListSerializer(serializers.ModelSerializer):
	class Meta:
		model = Album
		fields = ('id','name')

class AlbumSerializer(serializers.ModelSerializer):

	class TrackSerializer(serializers.ModelSerializer):
		class Meta:
			model = Track
			fields = ('id','title')

	class ArtistSerializer(serailizers.ModelSerializer):
		class Meta:
			model = Artist
			fields = ('id','title')

	name = serializers.CharField(min_length=2,max_length=100)
	tracks = TrackSerializer(many=True, read_only=True)
	artists = ArtistSerializer(many=True,read_only=True)
	~~albums = AlbumSerailizer(many=True, read_only=True)~~
	

	class Meta:
		model = Artist
		fields = ('id','name','artists','tracks')
  • validation ( C, U ) - Write
  • データ構造決定(R)-Read
  • >> jukebox/views.py
    from django.shortcuts import get_object_or_404
    from rest_framework.decorators import api_view
    from rest_framework.response import Response
    from .models import Artist, Album, Track
    from .serializers.artist import ArtistListSerializer,ArtistSerializer
    
    @api_view(['GET','POST'])
    def artist_list_or_create(request):
    
    	if request.method =='GET':
    		artists = Artist.objects.all()
    		serializer = ArtistlistSerializer(artists,many=True)
    		return Response(serializer.data)
    
    	elif request.method =='POST':
    		serializer = ArtistSerializer(data=request.data)
    		if serializers.is_valid(raise_exception=True):
    			serializer.save()
    			return Response(serializer.data)
    
    @api_view(['GET','PUT','DELETE'])
    def artist_detail_or_update_or_delete(request):
    	artist = get_object_or_404(Artist,pk=artist_pk)
    	if request.method =='GET':
    		serializer = ArtistSerializer(artist)
    		return Response(serializer.data)
    
    	elif request.method =='PUT':
    		serializer  = ArtistSerializer(instance=artist,data=request.data)
    		if serializer.is_valid(raise_exception = True):
    			serializer.save()
    			return Response(serializer.data)
      
    	elif request.method =='DELETE':
    		artist.delete()
    		return Response(data='delete successfully',status=status.HTTP_204_NO_CONTENT))