views:

263

answers:

1

Hi,

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

A: 

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)
S.Lott