0

我有一个多对多关系表,其中一些数据在连接库中

我的模型的基本版本如下所示:

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)

如果值不存在,我正在尝试使用 null 搜索特定行的每个值(基本上我正在尝试显示未填充值的空值的 fooval 表)典型的 sql 将是

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 模型对上述查询进行建模

谢谢

4

1 回答 1

0

Outer joins can be viewed as a hack because SQL lacks "navigation".

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

That's what an outer join really is -- an attempted lookup with a NULL replacement.

The only optimization is something like the following.

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)
于 2009-07-31T02:33:08.807 回答