1

I am new to Django and I am having dificulty of understanding how search Querys and work. I have these models:

User = settings.AUTH_USER_MODEL

class List(models.Model):
    user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL)
    name = models.CharField(max_length=200)

class ListShared(models.Model):
    shared_list = models.ForeignKey(List, on_delete=models.CASCADE, related_name="shared_list")
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sub_user")

Idea is that single user can have any number of lists and share those lists to other users if they choose to do so.

I am trying write three querys:

  1. Return all Lists created by user
  2. Return all Lists that are shared to user
  3. Return all above

So far it seems that 1. can be achieved with :

parent = User.objects.get(username=user_name)
lists = parent.list_set.all()

and 2. with:

lists = ListShared.objects.filter(user__exact=user)

But I can't seems to find a way to return every that user is connected to (3.). How can I achieve this?

1 Answer 1

2

You can filter with Q objects [Django-doc]:

from django.db.models import Q

List.objects.filter(Q(user=parent) | Q(shared_list__user=parent))

or if you do not need to fetch the User object itself, you can work with the user_name directly with:

from django.db.models import Q

List.objects.filter(Q(user__username=user_name) | Q(shared_list__user__username=user_name))
Sign up to request clarification or add additional context in comments.

1 Comment

This works almost perfectly. Only .distinct() is needed to ad at the end of the query to remove duplicate Lists. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.