将SQL查询转换为ORM查询

时间:2019-07-04 02:16:31

标签: mysql django orm

I have the following models

模型

class User(models.Model):
    ur_id = models.AutoField(primary_key=True)
    ur_mailid = models.CharField(max_length=100)
    ...

class User_info(models.Model):
    ui_id = models.AutoField(primary_key=True)
    # ui_iduser  = models.IntegerField()
    ui_iduser = models.ForeignKey(User, on_delete=models.CASCADE)
    ui_firstname = models.CharField(max_length=45)
    ui_lastname = models.CharField(max_length=45)
    ...

class User_group(models.Model):
    ug_id = models.AutoField(primary_key=True)
    ug_groupname = models.CharField(max_length=100)
    ...

class User_groupmember(models.Model):
    # ug_groupid = models.IntegerField()
    # ug_userid = models.IntegerField()
    ug_groupid = models.ForeignKey(User_group, on_delete=models.CASCADE)
    ug_userid = models.ForeignKey(User, on_delete=models.CASCADE)
    ...

这是SQL查询:

select 
      a.ur_id ur_id,
      c.ug_id ug_id,
      d.ui_mailid ui_mailid,
      d.ui_firstname ui_firstname,
      d.ui_lastname ui_lastname
    from user a
    LEFT OUTER JOIN 
        user_groupmember b ON a.ur_id = b.ug_userid
    LEFT OUTER JOIN 
        user_group c ON c.ug_id = b.ug_userid
    LEFT OUTER JOIN 
        user_info d ON d.ui_id = a.ur_id
    where a.ur_mailid = 'test@test.com' 

我需要在ORM查询中对其进行转换。

有没有不用原始SQL就能实现的方法吗?

感谢您的帮助

0 个答案:

没有答案