Is this MySQL Query
SELECT * from books WHERE ISBN = (SELECT isbn_id FROM userWishlist WHERE userid_id = request.user.id)
equivalent to this Django query?
q = userWishlist.objects.filter(userid_id = request.user.id).values('isbn_id')
return books.objects.filter(ISBN = q)
edit: Here are the models for userWishList and book
class books (models.Model):
ISBN = models.IntegerField(primary_key=True)
bookName = models.CharField(max_length=255)
bookVersion = models.CharField(max_length=255)
bookAuthor = models.CharField(max_length=255)
bookPublisher = models.CharField(max_length=255, default= 'NULL')
class wishlist (models.Model):
userid = models.ForeignKey(User, on_delete= models.CASCADE)
ISBN = models.ForeignKey(books, on_delete = models.CASCADE)
equivalent to this Django query?
No. Django expects a single value for equivalences, but the q
object is a QuerySet
of values.
Furthermore it is not necessary to use this. You can filter with:
books.objects.filter(wishlist__userid=request.user)
This will thus list all books for which a
wishlistexists which has as
useridthe
request.user`.
Note: Models in Django are written in PerlCase, not snake_case, so you might want to rename the model from
towishlist
Wishlist
.
Note: normally a Django model is given a singular name, so
Book
instead of.books
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments