I have been trying to generate a list of books that are not been reviewed by a user, ie the books for which he/she has not written a review for. Here are the essential details from my models.py:
class book(models.Model):
name = models.CharField(max_length=100)
isbn = models.CharField(max_length=15)
author = models.CharField(max_length=120)
year = models.CharField(max_length=15)
genre_name = models.IntegerField()
rating = models.IntegerField()
description = models.CharField(max_length=2000)
img = models.ImageField()
def __str__(self):
return self.name
class reviews(models.Model):
name = models.CharField(max_length=150)
bookid = models.IntegerField()
review = models.CharField(max_length=750)
rating = models.IntegerField(default=0)
def __str__(self):
return self.name
So, I have been trying to first get the books that the user has reviewed something like this:
books1 = reviews.objects.filter(name=username)
And to get the database of the books, I am doing the following:
allb = book.objects.all()
Initially, I just randomly generated 5 numbers in the range(1,132) and stored them in a array randb, something like this:
randb = []
for i in range(0,5):
randb.append(randint(1,132))
And then later linking those generated numbers to the book database that I retrieved in allb in the HTML part.
My main concern is when I do that, I end up getting the books which are already reviewed by the user, simply because I have not given any condition for that.
Note: I want to retrieve only those book ids which are not been reviewed by the user.
Further, I tried doing the following in order to filter it out:
books1 = reviews.objects.filter(name=username)
allb = book.objects.all()
randb = []
reviewed_books = books1.bookid /*I get error in this line: 'QuerySet' object has no attribute 'bookid'*/
count = 0
for i in range(0,132):
if i not in reviewed_books
randb.append(randint(1,132))
count = count + 1
if count == 5
break
I don't know how to make that line (the commented line in the above code) work. Need suggestions and some code snippet to make my code work.
Thank you in advance :)
EDIT: (I forgot the colons ':' after if statements)
books1 = reviews.objects.filter(name=username)
allb = book.objects.all()
randb = []
reviewed_books = books1.bookid /*I get error in this line: 'QuerySet' object has no attribute 'bookid'*/
count = 0
for i in range(0,132):
if i not in reviewed_books:
randb.append(randint(1,132))
count = count + 1
if count == 5:
break
You could try finding all books and then from that result, exclude books that have already been reviewed by the user:
book.objects.exclude(id__in=reviews.objects.filter(name=username).values_list('id', flat=True)