kaushik
kaushik

Reputation: 556

Django join query set based on condition

Models are given below:

class Workspace(models.Model):
    wid = models.AutoField(primary_key=True, validators=[MinValueValidator(1000)])
    wname = models.CharField(max_length=100)
    created_time = models.DateTimeField(auto_now_add=True)


class Invitation(models.Model):
    iid = models.AutoField(primary_key=True, validators=[MinValueValidator(1000)])
    invite_to = models.ForeignKey(User, related_name="invitation_uid2", on_delete=models.CASCADE)
    workspace = models.ForeignKey(Workspace, related_name="invitation_wid", on_delete=models.CASCADE)
    created_time = models.DateTimeField(auto_now_add=True)

I need to get the list of workspaces based on invite_to

"select * from Workspace where wid in (select workspace from Invitation where invite_to = 1)"

The above query in ORM type

Upvotes: 0

Views: 302

Answers (2)

Aurora Wang
Aurora Wang

Reputation: 1940

As I said in the comments, you can do it using Django's QuerySet:

Workspace.objects.filter(invitation_wid__invite_to__id=1)

Upvotes: 1

RHSmith159
RHSmith159

Reputation: 1592

If you've got the user id, you can use the double underscore __ syntax to filter across relations:

workspaces = Workspace.objects.filter(invitation_wid__invite_to__id=1)

Upvotes: 1

Related Questions