在外键的情况下请求django

时间:2015-01-12 10:15:15

标签: python django django-models django-templates django-views

我有两个表,作者和书,每本书都是由一个多作者写的,通过反对作者可以创建一个(一个)书,我想得到一个作者创建的书单。 在我的模板中,我会查看撰写一本书的作者

my models.py

class Book(models.Model):
        user = models.OneToOneField(User,related_name='user')
        name = models.CharField(default=0)
        def __unicode__(self):
                return u'%s' % self.user

class author(models.Model):
        name_auth = models.CharField(max_length=256)
        Book = models.ForeignKey(compte)
        def __unicode__(self):
                return u'%s' % (self.name_auth)

我的view.py

Book1 =Book.objects.filter(user=request.user).values()
Book1_id= Book1.id
author = Author.objects.filter(pk=Book1_id).values
reponse[author]=author

我的模板

 {% for t in author %}
                            <td>{{ t.name }}</td>

        {% endfor %}

1 个答案:

答案 0 :(得分:0)

根据你的陈述,模型中的逻辑是不正确的......

  

“一本书可以有多位作者”

您需要使用ManyToManyField来代表书籍的作者:

class Author(models.Model):
    user = models.OneToOneField(User)

    def __unicode__(self):
        return self.user.get_full_name()

class Book(models.Model):
    authors = models.ManyToManyField(Author)
    name = models.CharField(max_length=500)

    def __unicode__(self):
        return self.name


# views

from django.shortcuts import render, get_object_or_404

def book_detail(request, book_id):
    book = get_object_or_404(Book, id=book_id).prefetch_related('authors')

    return render(request, 'book_detail.html', {'book': book})


# book_detail.html

{% for author in book.authors.all %}
    {{ author }}
{% endfor %}