models 如下
from django.db import models
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=32)
price = models.DecimalField(max_digits=5, decimal_places=2)
pub_date = models.DateField()
publish = models.ForeignKey(
to="Publish", to_field="id", on_delete=models.CASCADE)
authors = models.ManyToManyField(to="Author")
class Publish(models.Model):
name = models.CharField(max_length=32)
city = models.CharField(max_length=32)
email = models.EmailField()
class Author(models.Model):
name = models.CharField(max_length=32)
age = models.IntegerField()
email = models.EmailField()
au_detail = models.OneToOneField(
to="AuthorDetail", to_field="id", on_delete=models.CASCADE)
class AuthorDetail(models.Model):
gender_choices = (
(0, '女'),
(1, '男'),
(2, '保密'),
)
gender = models.SmallIntegerField(choices=gender_choices)
tel = models.CharField(max_length=32)
address = models.CharField(max_length=64)
birthday = models.DateField()
我有个接口,想获取全部的book,包含详情信息:
代码如下:
def getList(request):
# 查询所有书籍 包含出版社信息 和 作者信息
bookList = Book.objects.filter(title='西游记').all()
dataLen = len(bookList)
result = []
for book in bookList:
authors = []
for i in book.authors.all():
author_dict = {
'name': i.name,
'age': i.age,
'email': i.email,
'au_detail': model_to_dict(i.au_detail)
}
authors.append(author_dict)
book_dict = {
'id': book.id,
'title': book.title,
'price': book.price,
'pub_date': book.pub_date,
'publish': model_to_dict(book.publish),
'authors': authors
}
result.append(book_dict)
return JsonResponse({
'data': result,
'length': dataLen,
'success': True,
}, safe=False)
def findBy(request):
# 通过书籍id查询详情
id = request.GET.get('id')
book = Book.objects.filter(id=id).first()
book_dict = model_to_dict(book)
book_dict['publish'] = model_to_dict(book.publish)
for author in book.authors.all():
book_dict['authors'] = model_to_dict(author)
book_dict['authors']['au_detail'] = model_to_dict(author.au_detail)
gender_choices = {
0: '女',
1: '男',
2: '保密'
}
book_dict['authors']['au_detail']['gender'] = gender_choices[book_dict['authors']
['au_detail']['gender']]
return JsonResponse({
'data': book_dict,
'success': True,
}, safe=False)
可以实现。总觉得这样好像很麻烦。请问是这样写的吗?