类型对象“书”没有属性“ order_by”

时间:2019-03-05 16:30:18

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

我有本书的模型:

class Book(models.Model):
    publish_house = models.ForeignKey(PublishHouse, on_delete=models.DO_NOTHING)
    author = models.ForeignKey(Author, on_delete=models.DO_NOTHING)
    title = models.CharField(max_length=50)
    price = models.DecimalField(max_digits=5, decimal_places=2)

    objects = models.Manager()

    img = models.ImageField(upload_to='books/', default='books/no.png')
    img_inside = models.ImageField(upload_to='books/', 
                              default='books/no_inside.png')
    is_available = models.BooleanField(default=True)
    book_date = models.DateTimeField(default=datetime.now, blank=True)
    is_best_selling = models.BooleanField()

    def __str__(self):
        return self.title

    class Meta:
        db_table = 'Book'

我想按日期在模板中显示书籍(显示最近添加的书籍),这是视图:

def index(request):
    new_books = Book.order_by('-book_date')[:4]
    bestselling_books = Book.objects.filter('is_best_selling')[:4]
    book_context = {
        'new_books': new_books,
        'bestselling_books': bestselling_books,
    }
    advertises = Advertise.objects.all()
    adv_context = {
        'advertises': advertises
    }
    return render(request, 'pages/index.html', adv_context, book_context)

我想按添加日期的顺序显示图书

它一直在显示该错误:

type object 'Book' has no attribute 'order_by'

2 个答案:

答案 0 :(得分:1)

书没有属性order_by,书的管理者有

所以您需要

Book.objects.order_by

答案 1 :(得分:1)

您需要更改此行

new_books = Book.objects.order_by('-book_date')[:4]

new_books = Book.objects.order_by('-book_date')[:4]

因为order_by在模型管理器中可用。

更新

def index(request):
    new_books = Book.order_by('-book_date')[:4]
    bestselling_books = Book.objects.filter(is_best_selling=True)[:4]
    advertises = Advertise.objects.all()
    book_context = {
        'new_books': new_books,
        'bestselling_books': bestselling_books,
        'advertises': advertises
    }

    return render(request, 'pages/index.html', book_context)