Kaito-a-bit / twitter_clone_app

This repository is for cloning twitter app⚡️
0 stars 0 forks source link

training_01: CSV output #19

Open Kaito-a-bit opened 2 years ago

Kaito-a-bit commented 2 years ago
Kaito-a-bit commented 2 years ago
Kaito-a-bit commented 2 years ago
def csv_export(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="books.csv"'
    writer = csv.writer(response)
    for book in Book.objects.all():
        row = [author for author in book.objects.all()]
        for author in book.coauthors.all():
            row.append(author.username)
        strAuthors = " ".join(row)
        writer.writerow([book.id, book.name, book.publisher.name, strAuthors, book.published_date])
    return response

短くする

def csv_export(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="books.csv"'
    writer = csv.writer(response)
    for book in Book.objects.all():
        strAuthors = " ".join([author.username for author in book.coauthors.all()])
        writer.writerow([book.id, book.name, book.publisher.name, strAuthors, book.published_date])
    return response

参考: Djangoのクエリセットから値を取得する方法