Tahir Patel
Tahir Patel

Reputation: 1

How to filter Django model data using the logged-in users with multiple objects

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

Answers (2)

Rojin
Rojin

Reputation: 1316

You can use {% if user.is_authenticated %} in the template as well.

Upvotes: 0

Jordan Mora
Jordan Mora

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

Related Questions