1。模型 图书和作者是多对多关系

class Book(models.Model):
book_name=models.CharField(max_length=40)
price=models.DecimalField(max_digits=4,decimal_places=2)
publish=models.ForeignKey(to="Publish",on_delete=models.CASCADE,related_name="publish")
author=models.ManyToManyField(to="Author",related_name="author")

class Meta:
db_table="tbl_book"

# def __str__(self):
# return self.book_name

class Publish(models.Model):
publish_name=models.CharField(max_length=20)
address=models.CharField(max_length=30)

class Meta:
db_table="tbl_publish"
# def __str__(self):
# return self.publish_name

class Author(models.Model):
sex_choices=[(0,"男"),(1,"女")]
name=models.CharField(max_length=20,unique=True)
phone=models.BigIntegerField()
sex=models.IntegerField(choices=sex_choices)

class Meta:
db_table="tbl_author"

# def __str__(self):
# return self.name

 

序列化器:

class SerBook(serializers.ModelSerializer):
""" add(1) add(1,2), set(list_object), remove(1), remove(1,2) or remove(*[1,2])"""
#publish = serializers.PrimaryKeyRelatedField(queryset=Publish.objects.all())
#author = serializers.PrimaryKeyRelatedField(allow_empty=False, many=True, queryset=Author.objects.all())
class Meta:
model=Book
fields="__all__"


class SerPublish(serializers.ModelSerializer):
class Meta:
model = Publish
fields = "__all__"

class SerAuthor(serializers.ModelSerializer):
class Meta:
model = Author
fields = "__all__"

 

视图以图书为例:

class BookView(APIView):


def get(self,request,*args,**kwargs):

pk= kwargs.get("id")
if pk :
inst = Book.objects.filter(id=kwargs.get("id")).first()
if inst:
ser = SerBook(instance=inst, many=False)
return Response(data=ser.data, status=200)
else:
return Response(data={"msg": "not found", "data": []}, status=200)
else:
inst = Book.objects.all()
ser = SerBook(instance=inst, many=True)
return Response(data=ser.data, status=200)


def post(self,request,*args,**kwargs):
data=request.data
many=False
if isinstance(data,list):
many=True
ser = SerBook(data=data, many=many)
if ser.is_valid():
ser.save()
return Response(data=ser.data, status=status.HTTP_200_OK)
else:
return Response(data=ser.errors, status=status.HTTP_404_NOT_FOUND)


def put(self,request,*args,**kwargs):
data=request.data
pk=kwargs.get("id")
if pk :
inst=Book.objects.filter(id=pk).first()
print(Book.objects.filter(id=pk).values().first(),"xxxx")
if inst:
ser = SerBook(instance=inst, many=False,data=data
)
if ser.is_valid():
ser.save()
return Response(data=ser.data, status=200)

 

 序列化器结构:

django  restframework 多对多模型_序列化

 

 

postman测试:

创建单个图书:

django  restframework 多对多模型_多对多_02

 

 

PUT  修改图书根据图书book  id:

django  restframework 多对多模型_多对多_03

 

多对多删除:

def delete(self,request,*args,**kwargs):
pk= kwargs.get("id")
data=request.data
if pk:
inst=Book.objects.filter(id=pk).first()
if inst:
inst.delete()
return Response(data={"code":200,"msg":"删除ok"})
else: return Response(data={"code":404,"msg":"删除失败,不存在!"})
else:
ids=data.get("ids")
if isinstance(ids,list):
objs=Book.objects.filter(id__in=ids)
objs.delete()
return Response(data={"code":200,"msg":"删除ok"})

 批量删除:

django  restframework 多对多模型_多对多_04