Reputation: 1
I am new to Django and trying to figure out how to filter data using the logged-in users with multiple objects.
When the user logged in, the user should be able to see the book which was authored by him, and also he is co-authored some books.
Models.py
class Book(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
co_authors = models.ManyToManyField(User, related_name='co_authored_by')
views.py
@login_required()
def booklist(request):
book=Book.objects.filter(author =request.user, co_authors =request.user)
context = {
'book':book
}
return render(request, "contracts/booklist.html", context)
Tried using Q and or logic not able pass both filters to the template.
Upvotes: 0
Views: 463
Reputation: 949
You should use Q
for complex lookups, in this case you need and OR (|)
operator
from django.db.models import Q
...
book=Book.objects.filter(Q(author=request.user) | Q(co_authors=request.user))
...
You can take a look at the docs.
Upvotes: 1