(1241,'操作数应包含1列')显示书列表

时间:2015-01-09 12:46:08

标签: django django-models

我有两个表,作者和书,每本书都是由一个作者写的,通过利弊,作者可以写多本书 在我的代码中,我想获得由单个作者创建的图书清单。

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

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)

模板

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

        {% endfor %}

2 个答案:

答案 0 :(得分:0)

您应该将外键放到Book型号:

class Author(models.Model):
    name_auth = models.CharField(max_length=256)

    def __unicode__(self):
            return self.name_auth

class Book(models.Model):
    user = models.OneToOneField(User, related_name='user')
    author = models.ForeignKey(Author)
    name = models.CharField()

    def __unicode__(self):
            return self.name

在您看来:

from django.shortcuts import render, get_object_or_404

def author_books(request):
    book = get_object_or_404(Book, user=request.user)
    return render(request, 'author_books.html', {'author': book.author})

模板:

{% for book in author.book_set.all %}
    <div>{{ book.name }}</div>
{% endfor %}

编辑user字段可能属于Author模型吗?如果是,那么:

class Author(models.Model):
    user = models.OneToOneField(User, related_name='user')
    name_auth = models.CharField(max_length=256)

    def __unicode__(self):
            return self.name_auth

class Book(models.Model):
    author = models.ForeignKey(Author)
    name = models.CharField()

    def __unicode__(self):
            return self.name

查看:

from django.shortcuts import render, get_object_or_404

def author_books(request):
    author = get_object_or_404(Author, user=request.user)
    return render(request, 'author_books.html', {'author': author})

模板将与上面相同。

答案 1 :(得分:0)

如果我改变了条件,每本书都是由一位多作者撰写的,通过反对作者可以创建一本(一本)书,我想获得由一位作者创作的书籍清单。在我的模板中,我会查看撰写一本书的作者