How to join two tables?

Hi all,

I have the following model:

class Collections(models.Model):
   ...
class Document(models.model):
  ...
class Users(models.Model):
   ...

class OpenDocuments(models.Model):
    user_id = models.ForeignKey(Users, on_delete=models.CASCADE)
    collection_id = models.ForeignKey(Collections, on_delete=models.CASCADE)
    document_id = models.ForeignKey(Documents, on_delete=models.CASCADE)

class SharedCollections(models.Model):
    collection_id = models.ForeignKey(Collections, on_delete=models.CASCADE)
    tofield= models.ForeignKey(Users, on_delete=models.CASCADE,null=True,related_name="tofield",to_field='email')

There is a collection class, and two classes (open & shared).
I want to get all documents from the table OpenDocuments where the user is the owner (i.e. is in OpenDocuments.user_id), but also the documents from the table OpenDocuments that are shared to the user (their collection_id is in the SharedCollections table, with the tofield = user).

Is there a way to do this? The original code (from Laravel) did a join between the tables OpenDOcuments & SharedCollections based on collection_id, and then some filtering.

Yes there is a way to do it.

It’s an “or” condition, so you would be creating your query with a Q object.

Your query is going to end up looking something like this:
OpenDocuments.objects.filter(Q(<user filter>) | Q(<shared collection filter>))