outer join modelisation in django

久未见 提交于 2019-12-12 04:25:08

问题


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)

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;

Is there any way to modelise above query using django model

Thanks


回答1:


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)


来源:https://stackoverflow.com/questions/1209947/outer-join-modelisation-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!