Home > Blockchain >  How to retrieve Django model object using ForeignKey?
How to retrieve Django model object using ForeignKey?

Time:05-22

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?

CodePudding user response:

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))
  • Related