1

I'm doing some querying currently and I was wondering if I would be able to query something from these 3 models where the return would give me all the projects the users are working on. I know about the basic filtering however thats not really enough in this case, how would one go about querying through 2 foreign keys.

class User(models.Model):
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    email = models.EmailField()

class ProjectUser(models.Model):
    project = models.ForeignKey("Project", on_delete=models.CASCADE)
    user = models.ForeignKey("User", on_delete=models.CASCADE)
    is_lead = models.BooleanField(default=False)

    class Meta:
        unique_together = (("project", "user"),)

class Project(models.Model):
    name = models.CharField(max_length=255)
    client = models.CharField(max_length=255)
    complete = models.BooleanField(default=False)

2
  • So you have a user and you want all the Projects that user is working on? Commented Jul 2, 2020 at 15:59
  • Yeah exactly, I wanted to get the query so then I can transform it into a JSON. Commented Jul 2, 2020 at 16:21

1 Answer 1

2

You can obtain the Projects a user is working on with:

Project.objects.filter(
    projectuser__user=user
)

The double underscores are used to look "through" relations. Furthermore the default related_query_name=… parameter [Django-doc] is, if not specified, the name of the model in lowercase.

Sign up to request clarification or add additional context in comments.

7 Comments

You're missing the suffix _set for the default related_name.
@schillingt: no, the query does not use related_name, it uses related_query_name in the filtering :) The confusion comes from the fact that if you specify a related_name, and no related_query_name, then it will indeed use the related_name. But if you do not specify any of the two, it uses the name of the model in lowercase.
@schillingt: see docs.djangoproject.com/en/dev/ref/models/fields/… where it shows how related_query_name is used in queries, and related_name as the name of the reverse manager.
So for every double __ you're able to look further into the databse if the fields are connected?
@Karna: yes, basically you can think of __ as some sort of LEFT OUTER JOIN: dofactory.com/sql/left-outer-join
|

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.