Linux下开发python django程序(django数据库多对多关系)

1.多对多关系数据访问

models.py设置

from django.db import models

# Create your models here.
sex_choices=(
('f','famale'),('m','male')
)
class User(models.Model):
    name = models.CharField(max_length=30)
    sex=models.CharField(max_length=1,choices=sex_choices)
    def __unicode__(self):
        return self.name

class Author(models.Model):
    name=models.CharField(max_length=30)
    def __unicode__(self):
        return self.name
class Book (models.Model):
    name = models.CharField(max_length=30)
    author=models.ManyToManyField(Author)
    def __unicode__(self):
        return self.name


views.py中调用

def index1(req):
     aus = Author.objects.all()
     books = Book.objects.all()
     t= loader.get_template('index1.html')
     c=Context({'aus':aus,'books':books})
     return HttpResponse(t.render(c))


templates中模板的设置

<body>
{% for book in books  %}
  <h1>书籍:{{book}}<br></h1>
  {% for au in book.author.all %}
    作者: {{au}}
    <br/>
  {%endfor%}
{% endfor%}

</body>

 

输出的结果:

 

posted @ 2016-09-21 17:40  whzym111  阅读(244)  评论(0编辑  收藏  举报