2013-07-22 26 views
2

我正在寻找使用Inner Join的特定原始SQL查询。Django - 对与PostgreSQL的多对多关系进行SQL查询内部加入

我有那些机型:

class EzMap(models.Model): 
    layers = models.ManyToManyField(Shapefile, verbose_name='Layers to display', null=True, blank=True) 


class Shapefile(models.Model): 
    filename = models.CharField(max_length=255) 


class Feature(models.Model): 
    shapefile = models.ForeignKey(Shapefile) 

我想作一个SQL查询有效PostgreSQL的,将是这样一个:

select id from "table_feature" where' shapefile_ezmap_id = 1 ; 

但我不知道如何使用INNER JOIN以过滤features其中shapefile它们所属的与特定的ezmap对象

回答

1

所以mething这样的:

try: 
    id = Feature.objects.get(shapefile__ezmap__id=1).id 
except Feature.DoesNotExist: 
    id = 0 # or some other action when no result is found 

你需要,如果你要处理多个Feature结果使用(而不是getfilter

+0

非常感谢。然后使用QuerySet.query,我可以得到我需要的原始SQL查询 –