我有一个Book模型,有多个作者,流派。以下是具有所有ForeignKey关系的模型。
models.py
class Book(models.Model):
title = models.CharField(max_length=200)
class Author(models.Model):
name = models.CharField(max_length=100)
class Genre(models.Model):
genre_name = models.CharField(max_length=50)
class Book_author(models.Model):
book = models.ForeignKey(Book)
author = models.ForeignKey(Author)
class Book_genre(models.Model):
book = models.ForeignKey(Book)
genre = models.ForeignKey(Genre)
views.py
def book_detail(request, book_id):
book = Book.objects.get(pk=book_id)
# how can i get iterated multiple authors, books attached to book dictionary
return render(request, 'detail.html', {'book': book})
图书对象示例:
book = {
title: 'some title',
authors: [
{
id: 1,
name: 'name1'
},
{
id: 2,
name: 'name2'
}
],
genres: [
{
id: 1,
genre_name: 'somegenre1'
},
{
id: 1,
genre_name: 'somegenre2'
}
]
}
如何在我的views.py方法中访问与图书相关的作者,类型
答案 0 :(得分:1)
您不需要更改视图中的任何内容,对于反向查找,您可以调用模型的反向关系访问器并利用所有相关对象。
在您的模板中
private transient PreparedStatement selectAssetClassStmt;
selectAllAssetClassesStmt = cassandraDatasource.getSession().prepare("select code,description from asset_class where code = ?");