外连接模型化在django [英] outer join modelisation in django
问题描述
我有很多关系表,在联合基础中有一些数据
I have a many to many relationship table whith some datas in the jointing base
我的模型的基本版本看起来像:
a basic version of my model look like:
class FooLine(models.Model):
name = models.CharField(max_length=255)
class FooCol(models.Model):
name = models.CharField(max_length=255)
class FooVal(models.Model):
value = models.CharField(max_length=255)
line = models.ForeignKey(FooLine)
col = models.ForeignKey(FooCol)
如果值不存在,我试图搜索某个行的某个行的每个值(基本上我正在尝试显示没有填充的值的空值的fooval表)
a典型值sql将是
I'm trying to search every values for a certain line with a null if the value is not present (basically i'm trying to display the fooval table with null values for values that haven't been filled) a typical sql would be
SELECT value FROM FooCol LEFT OUTER JOIN
(FooVal JOIN FooLine
ON FooVal.line_id == FooLine.id AND FooLine.name = "FIXME")
ON FooCol.id = col_id;
有没有办法使用django模型来模拟上述查询
Is there any way to modelise above query using django model
谢谢
推荐答案
外连接可以被视为黑客,因为SQL缺少导航。
Outer joins can be viewed as a hack because SQL lacks "navigation".
你有一个简单的if-statement情况。
What you have is a simple if-statement situation.
for line in someRangeOfLines:
for col in someRangeOfCols:
try:
cell= FooVal.objects().get( col = col, line = line )
except FooVal.DoesNotExist:
cell= None
这是外连接真的是 - 一次尝试查找一个NULL替换。
That's what an outer join really is -- an attempted lookup with a NULL replacement.
唯一的优化是如下。
matrix = {}
for f in FooVal.objects().all():
matrix[(f.line,f.col)] = f
for line in someRangeOfLines:
for col in someRangeOfCols:
cell= matrix.get((line,col),None)
这篇关于外连接模型化在django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!