Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type object 'Book' has no attribute 'order_by'

I have a model for book:

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'

I want to display books in templates by date (showing books that added recently), and this is the view:

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)

i want to display books in order by the date they were added

it keeps giving that error:

type object 'Book' has no attribute 'order_by'
like image 755
Aya Avatar asked Dec 08 '25 19:12

Aya


1 Answers

Book doesn't have an attribute order_by, its manager does

So you need

Book.objects.order_by
like image 162
Sayse Avatar answered Dec 11 '25 08:12

Sayse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!