【问题标题】:type object 'Book' has no attribute 'order_by'类型对象“Book”没有属性“order_by”
【发布时间】:2019-07-27 04:36:13
【问题描述】:

我有一个书模型:

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'

【问题讨论】:

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


    【解决方案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)
    

    【讨论】:

    • 在教程中他没有添加 .objects,但我尝试添加它,它给了我错误:解包的值太多(预期 2)
    • 还是一样
    • 这行可能会出现return render(request, 'pages/index.html', adv_context, book_context)
    • 我删除了 bestselling_books = Book.objects.filter('is_best_selling')[:4]'bestselling_books': bestselling_books 并停止了错误,但在模板中它不显示任何书籍并显示我写的内容出现在 else 语句中没有找到书的情况
    • is_best_selling = models.BooleanField() 我添加了default=False 作为参数,它解决了它
    【解决方案2】:

    书没有属性order_by,它的经理有

    所以你需要

    Book.objects.order_by
    

    【讨论】:

      猜你喜欢
      • 2023-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      • 2021-03-20
      相关资源
      最近更新 更多