Below the Radar
Below the Radar

Reputation: 7635

Django - Making a SQL query on a many to many relationship with PostgreSQL Inner Join

I am looking for a perticular raw SQL query using Inner Join.

I have those models:

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)

I would like to make a SQL Query valid with PostgreSQL that would be like this one:

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

but I dont know how to use the INNER JOIN to filter features where the shapefile they belongs to are related to a particular ezmap object

Upvotes: 2

Views: 599

Answers (1)

Matt
Matt

Reputation: 10322

Something like this:

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

You will need to use filter (instead of get) if you want to deal with multiple Feature results.

Upvotes: 1

Related Questions