1

I have a Books table where I want to retrieve all records based on different column values

e.g

Select * from Books where bookid = 2 || bookid = 3 || bookid = 4; 

The book ids I get is from a Rent table:

    rents =Rents.objects.filter(user=request.user)

So I have a queryset of rents object that contains a property bookid.

How do I get Books based on all the values of the rents?

bawagoc25
  • 33
  • 3

2 Answers2

0

Whats the difference between a OneToOne, ManyToMany, and a ForeignKey Field in Django?

Check this out. It also tells you aboue how Django let you view relationships in reverse order.

Yash Malviya
  • 21
  • 1
  • 6
0

You can use Q objects for doing or or and operations. Here is the example:

from django.db.models import Q    # import Q object for queryset

rents = Rents.objects.filter(Q(bookid__exact=2) | Q(bookid__exact=3) | Q(bookid__exact=4), user=request.user)

rents will have objects with user logged user having book_id of 2 or 3 or 4. I don't know how your models are structured, but this is one of the way to do so.

Here is the reference from docs.

EDIT

Q object is provided, it must precede the definition of any keyword argument. But, I was just doing exact opposite.

Biplove Lamichhane
  • 3,995
  • 4
  • 14
  • 30