显示模型及其关系 [英] Display model and its relations

查看:52
本文介绍了显示模型及其关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的models.py如下:

My models.py is as follows:

from django.db import models

class Book(models.Model):
    book_id=models.AutoField(primary_key=True,unique=True)
    book_name=models.CharField(max_length=30)
    author_name=models.CharField(max_length=30)
    publisher_name=models.CharField(max_length=40)
    def __unicode__(self):
        return "%d %s %s %s" % (self.book_id,self.book_name, self.author_name,self.publisher_name)


class Author(models.Model):
    author_id=models.AutoField(primary_key=True)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    age=models.IntegerField()
    book=models.ForeignKey(Book)

    def __unicode__(self):
        return u'%d %s %s' % (self.author_id,self.first_name, self.last_name)

和我的views.py是这样的:

and my views.py is this:

def index(request):

    books = Book.objects.all()
    context={'books':books}
    return render(request,'index.html', context)

以上views.py在Book类中显示内容,但我无法在作者表中显示内容。我的要求是显示合并在单个页面中的两个内容。请帮我做到这一点。

The above views.py displays contents in the Book class, but I am not able to display the contents in the author table. My requirement is to display both contents merged in a single page. Please help me do this.

推荐答案

models.py

class Book(models.Model):
    book_name=models.CharField(max_length=30)
    author_name=models.CharField(max_length=30)
    publisher_name=models.CharField(max_length=40)
    author=models.ForeignKey(Author)

    def __unicode__(self):
        ..........

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    age=models.IntegerField()

    def __unicode__(self):
        ........

    def books(self):
        return Book.objects.filter(author=self)

views.py

def index(request):
    authors = Author.objects.all()
    context={'authors':authors}
    return render(request,'index.html', context)

模板

{% for author in authors %}
    Author: {{author.first_name}} {{author.last_name}}<br/>
    Email: {{author.email}}
    Age: {{author.age}}
    Books:
        {% for book in author.books %}
            .......
        {% endfor %}
{% endfor %}

这篇关于显示模型及其关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆