完成序列化的整理

main
RogerWork 1 year ago
parent 2f64c4a7ab
commit cca302e610
  1. 19
      apps/basic/migrations/0005_alter_address_create_date.py
  2. 19
      apps/goods/migrations/0005_alter_goods_create_datetime.py
  3. 0
      apps/music/__init__.py
  4. 3
      apps/music/admin.py
  5. 7
      apps/music/apps.py
  6. 34
      apps/music/migrations/0001_initial.py
  7. 0
      apps/music/migrations/__init__.py
  8. 17
      apps/music/models.py
  9. 51
      apps/music/serializer.py
  10. 3
      apps/music/tests.py
  11. 9
      apps/music/urls.py
  12. 24
      apps/music/views.py
  13. 27
      myshop_back/settings.py
  14. 3
      myshop_back/urls.py

@ -0,0 +1,19 @@
# Generated by Django 4.2.4 on 2023-09-05 00:33
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('basic', '0004_alter_address_create_date'),
]
operations = [
migrations.AlterField(
model_name='address',
name='create_date',
field=models.DateTimeField(default=datetime.datetime(2023, 9, 5, 8, 33, 2, 815984), verbose_name='创建时间'),
),
]

@ -0,0 +1,19 @@
# Generated by Django 4.2.4 on 2023-09-05 00:33
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('goods', '0004_alter_goods_create_datetime'),
]
operations = [
migrations.AlterField(
model_name='goods',
name='create_datetime',
field=models.DateTimeField(default=datetime.datetime(2023, 9, 5, 8, 33, 2, 822232), verbose_name='创建时间'),
),
]

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

@ -0,0 +1,7 @@
from django.apps import AppConfig
class MusicConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apps.music'
verbose_name = '音乐'

@ -0,0 +1,34 @@
# Generated by Django 4.2.4 on 2023-09-05 00:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Musician',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=50)),
('last_name', models.CharField(max_length=50)),
('instrument', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='Album',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('release_date', models.DateField()),
('num_stars', models.IntegerField()),
('artist', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='album_musician', to='music.musician')),
],
),
]

@ -0,0 +1,17 @@
from django.db import models
class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
def __str__(self):
return self.first_name
class Album(models.Model):
artist = models.ForeignKey(Musician, on_delete=models.CASCADE, related_name='album_musician', null=True, blank=True)
name = models.CharField(max_length=100)
release_date = models.DateField()
num_stars = models.IntegerField()

@ -0,0 +1,51 @@
from rest_framework import serializers, fields
from apps.music.models import *
class AlbumSerializer(serializers.ModelSerializer):
class Meta:
model = Album
fields = ('id', 'artist', 'name', 'release_date', 'num_stars')
class MusicianSerializer(serializers.ModelSerializer):
# album_musician = AlbumSerializer(read_only=True, many=True) # 定义只读外键字段后在fields中添加此键
album_musician = AlbumSerializer(many=True) # 定义只读外键字段后在fields中添加此键,如果需要写入create和update方法,则不应设置readonly
class Meta:
model = Musician
fields = ('id', 'first_name', 'last_name', 'instrument', 'album_musician')
# 定义创建数据的方法,用于处理外键的存储
def create(self, validated_data):
print(validated_data)
albums_data = validated_data.pop('album_musician') # 将album_musician对应的数据取出,还原Musician的原始数据格式
musician = Musician.objects.create(**validated_data) # 将musician数据入库, 获取返回的musician_id
print(musician)
for album in albums_data:
Album.objects.create(artist=musician, **album) # 遍历albums数据将数据入库
return musician
# 定义创修改的方法,用于处理外键存储
def update(self, instance, validated_data): # instance为pk指定的数据库对象实例
print(instance)
print(validated_data)
albums_data_req = validated_data.pop('album_musician') # 将album_musician对应的数据取出,还原Musician的原始数据格式
albums_db = instance.album_musician.all() # 获取原始的album外键数据
albums_db = list(albums_db)
print(albums_db)
# 从validated_data中获取字段的值,如果没有获取到就取数据库实例的对应值,并且更新数据
instance.first_name = validated_data.get('first_name', instance.first_name)
instance.last_name = validated_data.get('last_name', instance.last_name)
instance.instrument = validated_data.get('instrument', instance.instrument)
instance.save()
# 更新album数据
for album_data_req in albums_data_req:
album_db = albums_db.pop(0)
album_db.name = album_data_req.get('name', album_db.name)
album_db.release_date = album_data_req.get('release_date', album_db.release_date)
album_db.num_stars = album_data_req.get('num_stars', album_db.num_stars)
album_db.save()
return instance

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

@ -0,0 +1,9 @@
from django.urls import path, re_path
from apps.music.views import *
urlpatterns = [
re_path(r'^api/musician/$', MusicianListView.as_view()),
re_path(r'^api/musician/(?P<pk>\d+)/$', MusicianView.as_view()),
re_path(r'^api/album/$', AlbumListView.as_view()),
re_path(r'^api/album/(?P<pk>\d+)/$', AlbumView.as_view()),
]

@ -0,0 +1,24 @@
from rest_framework import generics
from apps.music.models import *
from apps.music.serializer import *
class MusicianListView(generics.ListCreateAPIView):
queryset = Musician.objects.all().order_by('id')
serializer_class = MusicianSerializer
class MusicianView(generics.RetrieveUpdateDestroyAPIView):
queryset = Musician.objects.all().order_by('id')
serializer_class = MusicianSerializer
class AlbumListView(generics.ListCreateAPIView):
queryset = Album.objects.all().order_by('id')
serializer_class = AlbumSerializer
class AlbumView(generics.RetrieveUpdateDestroyAPIView):
queryset = Album.objects.all().order_by('id')
serializer_class = AlbumSerializer

@ -41,6 +41,7 @@ INSTALLED_APPS = [
'apps.goods',
'apps.order',
'apps.user',
'apps.music',
'ckeditor',
'ckeditor_uploader',
'rest_framework',
@ -164,20 +165,20 @@ REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'common.myexception.my_exception_handler',
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
# 验证设置
'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',),
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
}
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=3), # 配置过期时间
'JWT_AUTH_HEADER_PREFIX': 'JWT', # 配置Token的前缀
'JWT_ALLOW_REFRESH': False, # 是否允许刷新
'JWT_RESPONSE_PAYLOAD_HANDLER': 'common.myjwt.jwt_response_payload_handler',
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=30), # token有效时长
'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=1), # token刷新有效时长
# 'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',),
# 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
}
# JWT_AUTH = {
# 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=3), # 配置过期时间
# 'JWT_AUTH_HEADER_PREFIX': 'JWT', # 配置Token的前缀
# 'JWT_ALLOW_REFRESH': False, # 是否允许刷新
# 'JWT_RESPONSE_PAYLOAD_HANDLER': 'common.myjwt.jwt_response_payload_handler',
# }
#
# SIMPLE_JWT = {
# 'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=30), # token有效时长
# 'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=1), # token刷新有效时长
# }
# 跨域配置
CORS_ALLOW_CREDENTIALS = True # 跨域时是否携带cookie

@ -21,5 +21,6 @@ urlpatterns = [
path('admin/', admin.site.urls),
path('user/', include('apps.user.urls')),
path('basic/', include('apps.basic.urls')),
path('goods/', include('apps.goods.urls'))
path('goods/', include('apps.goods.urls')),
path('music/', include('apps.music.urls')),
]

Loading…
Cancel
Save