2012-02-08 5 views
0

複数のモデル(外部キー)のデータを表形式で表示しようとしています。複数モデルのデータをDjangoのフラットテーブルにリストする

class Author(models.Model): 
    name = models.CharField(max_length=250) 

class Book(models.Model): 
    title = models.CharField(max_length=250) 
    isbn = models.CharField(max_length=250) 
    author = models.ManyToManyField(Author) 

予想される出力:

  • ブック1 - isbn1 - Author1
  • ブック1 - isbn1 - Author2
  • ブック2 - isbn2 - Author3
  • ブック3 - isbn3 - 著者1

これで、さまざまなフィルタを使用して2つのモデルにクエリを行い、対応するリストオブジェクトを持つことができました。これら2つのリストオブジェクトを少ないコードでテンプレートに表示するにはどうすればよいですか?

私が考えることの1つの方法は、これらの2つのリストを反復し、列の対応するキーを持つdictのリストを作成し、このリストをテンプレートに渡すことです。これにはよりよいアプローチがありますか?

現在のコード

def getresult(params): 
    print "printing dict ", params 
    titles = params.getlist('titles') 
    authors_input = params.getlist('authors') 
    ... 
    books = Book.objects.all() 
    if len(title) > 0 : 
     books = books.objects.filter(title__in = titles) 
    ... 
    authors = Authors.objects.filter(name__in=books) 
    if len(authors_input) > 0 : 
     authors = authors.filter(name__in = authors_input) 
    result = [] 
    for book in books: 
     authors = authors.filter(name=book.author) 
     for author in authors: 
      output_item = {} 
      output_item['book_name'] = book.title 
      output_item['isbn'] = book.isbn 
      output_item['author'] = author.name 
      result.append(output_item) 
    return result 
+0

は私達にあなたの現在のコードを表示します。 – Marcin

+0

@Marcinの現在のコードは – butters

答えて

1

これが一般的なパターンであるので、これの世話をgeneric viewがあります。ここのコードスニペットは、ドキュメントから直接得られたもので、独自のケースで修正されています。

urls.py

from django.conf.urls.defaults import * 
from django.views.generic import ListView 
from myapp.models import Book 

urlpatterns = patterns('', 
    (r'^books/$', ListView.as_view(
     model=Book, 
    )), 
) 

はどこかTEMPLATE_DIRSにある場所でmyappというディレクトリにbook_list.htmlと呼ばれるテンプレートを作成します。テンプレート(book_list.html)で

このスニペットは何が必要ありません:

<ul> 
{% for book in object_list %} 
    {% for author in book.author_set.all %} 
    <li>{{ book.title }}&mdash;{{ book.isbn }}&mdash;{{ author.name }}</li> 
    {% endfor %} 
{% endfor %} 
</ul> 
+0

と掲載されています。自分のフィルタ条件に基づいて本と著者オブジェクトをフィルタリングできますか? – butters

+0

はい。ジェネリックビューの[documentation](https://docs.djangoproject.com/ja/1.3/topics/class-based-views/#generic-views-of-objects)を読んでください。 –

関連する問題