At first step I will describe my models:

class Meter(models.Model):
    id = models.IntegerField(primary_key=True)

    ........some stuff here...

    collector = models.ManyToManyField("self",
through='MeterCollector', symmetrical=False)

class MeterCollector(models.Model):
    meter = models.ForeignKey(Meter, related_name='meter_id')
    collector_node = models.ForeignKey(Meter,
related_name='collecotor_node_id')

    def __unicode__(self):
        return u'meter id: %s; collector node id: %s;' %
( self.meter_id, self.collector_node_id)

    class Meta:
        db_table = 'meter_to_collector'

class MeterSspec(models.Model):
    id = models.IntegerField(primary_key=True)
    meter = models.ForeignKey(Meter)
    sspec = models.ForeignKey(Sspec)
    ......some stuff...

Everything works fine until I use filter like this in view.py:

meter_list = Meter.objects.all().filter(meter__metersspec__sspec =
sspec_id)

I expect something like "Give me all meters that have sspec_id = 1",
so my custom query will be:

SELECT `meter`.`id`, `meter`.`description`  FROM `meter` LEFT JOIN
`meter_to_collector` ON (`meter`.`id` =
`meter_to_collector`.`collector_node_id`) LEFT JOIN  `meter` T3 ON
(`meter_to_collector`.`meter_id` = T3.`id`) INNER JOIN `meter_sspec`
ON (`meter`.`id` = `meter_sspec`.`meter_id`) WHERE
`meter_sspec`.`sspec_id` = '1'

But django gives me something like this:

 SELECT `meter`.`id`, `meter`.`description` FROM `meter` INNER JOIN
`meter_to_collector` ON (`meter`.`id` =
`meter_to_collector`.`collector_node_id`) INNER JOIN
 `meter` T3 ON (`meter_to_collector`.`meter_id` = T3.`id`) INNER JOIN
`meter_sspec` ON (T3.`id` = `meter_sspec`.`meter_id`) WHERE
`meter_sspec`.`sspec_id` = '1'

There are 2 common problems:
1) How can I force django  to use LEFT JOIN ???
2) Genreal problem: Im wondering why django joins meter_sspec with
meter_to_collector (T3) and not with meter???

So, is there any way to do it without custom sql query ?

Alex M Vdovin.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to