Aya
Aya

Reputation: 37

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'

Upvotes: 3

Views: 926

Answers (2)

shafikshaon
shafikshaon

Reputation: 6404

You need to change this line

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

to

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

because order_by is available in model manager.

Update:

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)

Upvotes: 1

Sayse
Sayse

Reputation: 43330

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

So you need

Book.objects.order_by

Upvotes: 1

Related Questions