请教个django的orm问题?

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)

可以实现。总觉得这样好像很麻烦。请问是这样写的吗?

阅读 837
2 个回答
from django.forms.models import model_to_dict

def book_to_dict(book):
    authors_data = []
    for author in book.authors.all():
        author_data = model_to_dict(author)
        author_data['au_detail'] = model_to_dict(author.au_detail)
        gender_choices = {
            0: '女',
            1: '男',
            2: '保密'
        }
        author_data['au_detail']['gender'] = gender_choices[author_data['au_detail']['gender']]
        authors_data.append(author_data)
    
    return {
        'id': book.id,
        'title': book.title,
        'price': book.price,
        'pub_date': book.pub_date,
        'publish': model_to_dict(book.publish),
        'authors': authors_data
    }

def getList(request):
    books = Book.objects.filter(title='西游记').select_related('publish').prefetch_related('authors', 'authors__au_detail')
    books_data = [book_to_dict(book) for book in books]
    return JsonResponse({
        'data': books_data,
        'length': len(books_data),
        'success': True,
    }, safe=False)

def findBy(request):
    book_id = request.GET.get('id')
    book = Book.objects.filter(id=book_id).select_related('publish').prefetch_related('authors', 'authors__au_detail').first()
    if not book:
        return JsonResponse({
            'error': 'Book not found',
            'success': False
        }, status=404)
    book_data = book_to_dict(book)
    return JsonResponse({
        'data': book_data,
        'success': True,
    }, safe=False)

使用 select_related

直接一步到位

books = Book.objects.filter(title='西游记').select_related('authors__au_detail').all()
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题