Django - objects.values() and prefetch_related() in same query

前端 未结 2 1040
萌比男神i
萌比男神i 2021-01-14 10:56

I have Book, Profile, Book_stat model as below. I am trying to minimize the fields from Book model and prefetch_related method to get the data from Book_s

2条回答
  •  迷失自我
    2021-01-14 11:52

    Instead the values method you can use the only and serialize manually:

    from django.db.models import Prefetch
    from django.forms import model_to_dict
    from django.http import JsonResponse
    
    def books(request):
        prefetch = Prefetch('book_stat_set', queryset=Book_stat.objects.only('like', 'rating'))
        qs = Book.objects.prefetch_related(prefetch).only('id','title', 'image')
        result = []
        for book in qs:
            row = model_to_dict(book, fields=['id','title', 'image'])
            row['image'] = row['image'].url
            stats = []
            for book_stat in book.book_stat_set.all():
                stat = model_to_dict(book_stat, fields=['like', 'rating'])
                stat['rating'] = str(stat['rating'])  # or float(stat['rating']) - depends on your purposes
                stats.append(stat)
            # you can calculate an average rating here
            row['stats'] = stats
            result.append(row)
        return JsonResponse(result)
    

提交回复
热议问题