Convert mysql query to django orm with requires same table
I am trying to convert sql code to django orm code. I don't want to use python raw function
SELECT
u.`user_id` as 'dp_id',
cp.`email` as 'dp_email',
cp.`name` as 'dp_name',
u2.`user_id` as 'cm_id',
cp2.`email` as 'cm_email',
cp2.`name` as 'cm_name'
FROM `user` u
INNER JOIN customer_profile cp
ON u.`customer_profile_id` = cp.`id`
INNER JOIN branch_user bm
ON bm.`child_user_id` = u.`user_id`
AND bm.`parent_role_id` = 14
AND bm.`is_deleted` = 0
INNER JOIN user u2
ON u2.`user_id` = bm.`parent_user_id`
AND u2.`is_deleted` = 0
INNER JOIN customer_profile cp2
ON u2.`customer_profile_id` = cp2.`id`
WHERE u.`user_id` = ?
AND u.`is_deleted` = 0
I did something like this :
cp_emails = User.objects.filter(branch_user_childUser__parent_role_id=14, branch_user_childUser__is_deleted=0).select_related('customer_profile').prefetch_related('branch_user_childUser')
But i am not able to add user u2 to django orm as it's same user table and that too compare with "bm" i.e this line "ON u2.user_id = bm.parent_user_id"
My models:
class User(models.Model):
user_id = models.AutoField(primary_key=True)
customer_profile = models.ForeignKey(
'login.CustomerProfile', on_delete=models.CASCADE, default=None
)
class BackboneUserManagerMapping(models.Model):
child_user = models.ForeignKey('login.User', related_name='branch_user_childUser', on_delete=models.DO_NOTHING)
parent_user = models.ForeignKey('login.User', related_name='branch_user_childUser', on_delete=models.DO_NOTHING)
parent_role_id = models.IntegerField()
is_deleted = models.BooleanField(default=False)
class CustomerProfile(AbstractBaseUser, PermissionsMixin):
id = models.AutoField(primary_key=True)
email = models.EmailField(default=None, unique=True)
mobile = models.CharField(max_length=13, default=None)
alt_mobile = models.CharField(max_length=13, null=True)
name = models.CharField(max_length=255, default=None)