在Django中从外键关系的两个表检索数据? [英] Retrieve data from two tables with foreign key relationship in Django?

查看:166
本文介绍了在Django中从外键关系的两个表检索数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  This is my models.py file 


 from django.db import models

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

        class Meta:
        db_table=u'Author Info'

        def __unicode__(self):
            return u"%d %s %s %s" % (self.pk, self.name, self.author.name, self.publisher_name)

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

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

        class Meta:
            db_table = u'Book Name'

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

我想从2个表中减去数据,在django中。请指导我如何在authors表中使用foreignkey来编写views.py和templates.i

I want to diaplay the datas from 2 tables,in django.Please guide me how to write views.py and templates.i am using foreign key in author table

推荐答案

以下内容视图和html用于显示具有腐蚀性作者详细信息的所有图书。

The Following views and html is used for display all books with corrosponding author details.

views.py

def client_add(request):
   books = Book.objects.all()
   return render_to_response('book_details.html', locals(),    context_instance=RequestContext(request))

book_details.html

book_details.html

<body>
{% for book in books %}
{{book.book_name}}
{{book.publisher_name}}
{{book.author.first_name}}
{{book.author.last_name}}
{{book.author.email}}
{{book.author.age}}
{% endif %}
</body>

以下视图和html用于特定作者腐蚀性细节的展示书。

The Following views and html is used for display books for particular author corrosponding details.

views.py

def client_add(request):
   books = Book.objects.all(author_last_name ="author_last_name")
   return render_to_response('book_details.html', locals(),    context_instance=RequestContext(request))

book_details.html

book_details.html

<body>
{% for book in books %}
{{book.book_name}}
{{book.publisher_name}}
{{book.author.first_name}}
{{book.author.last_name}}
{{book.author.email}}
{{book.author.age}}
{% endif %}
</body>

这篇关于在Django中从外键关系的两个表检索数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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