我有以下型号:
class Sld(models.Model):
sld_name = models.CharField(max_length=63, unique=True)
tld = models.ForeignKey('db.Tld', on_delete=models.PROTECT)
class Tld(models.Model):
tld_name = models.CharField(max_length=20)
class Path(models.Model):
path_name = models.CharField(max_length=255)
sld = models.ForeignKey('db.Sld', on_delete=models.CASCADE)
我想使用Django的ORM执行以下查询:
SELECT
t1.path_name,
t2.sld_name,
t3.tld_name
FROM path t1
LEFT JOIN sld t2
ON (t2.id = t1.sld_id)
LEFT JOIN tld t3
ON (t2.tld_id = t3.id);
以下是一些尝试:
urls = Path.objects.select_related().values('sld_name', 'tld_name', 'path_name')
urls = Path.objects.all().select_related().values()
urls = Path.objects.select_related('sld').select_related('tld').values()
我在这里想念什么?
数据应如下所示:
{
'sld_name':'google',
'tld_name':'com',
'path_name':'/'
}
...
答案 0 :(得分:1)
您可以执行以下操作:
urls = Path.objects.values('sld__sld_name', 'sld__tld__tld_name', 'path_name')
无需再用select_related
来打values
,因为它只获取一个具有您所需所有值的请求。