I am looking for a way to build query with a JOIN relation (not INNER JOIN) with custom ON condition.
I have 2 models
class User(models.Model):
email = models.EmailField(unique=True)
name = models.CharField(max_length=100, null=True, blank=True)
class Company(models.Model):
name = models.CharField(max_length=100, null=True, blank=True)
foo = models.BooleanField(default=False)
email_domain = models.CharField(max_length=100, null=True, blank=True, help_text='Email domain without @')
I want to find all users whose email address matches with domain name of a company. The company must have an email_domain and foo must be True.
I have managed to get the result with raw query :
raw = """SELECT DISTINCT
u.id, u.name, u.email
FROM myapp_user AS u
JOIN myapp_company AS c
ON c.foo = True
AND c.email_domain IS NOT NULL
AND u.email LIKE CONCAT('%%', '@', c.email_domain)"""
query = User.objects.raw(raw)
But is there a way to build the query using django ORM ? I tried with FilteredRelation but I can't figure out how to use it in my case.