Spatial Digger
Spatial Digger

Reputation: 1993

Filtering based on a foreign key in Django

I'm trying to filter a table based on a value in another table, via a foreign key.

trench_id = models.ForeignKey(Trench, db_column='trench_id', on_delete = models.PROTECT)

As above, the Context model joins to the Trench model via trench_id__trench_id I want to access trench.name as you can see below I'm then using this value in a filter. I include the views.py code and for reference my models.py.

def allcontexts(request):
    allcontexts = Context.objects.filter(trench_id__trench_id__name=request.session.get("name"))
    return render(request, 'context_manager/context_manager.html',
    {
    'allcontexts':allcontexts,
    })

I'm getting the following error Unsupported lookup 'name' for AutoField or join on the field not permitted.

models.py

class Trench(models.Model):
    trench_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=50)
    area_easting = models.IntegerField()
    area_northing = models.IntegerField()

    def __str__(self):
        return str(self.name)

class Context(models.Model):
    context_id = models.AutoField(primary_key=True)
    trench_id = models.ForeignKey(Trench, db_column='trench_id', on_delete = models.PROTECT)
    number = models.IntegerField()
    type = models.CharField(max_length = 50, blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    excavation_method = models.CharField(max_length = 50, blank=True, null=True)
    open_date = models.DateField(blank=True, null=True)
    close_date = models.DateField(blank=True, null=True)
    excavated_by = models.CharField(max_length = 50, blank=True, null=True)
    area_easting = models.IntegerField()

    def __str__(self):
        return str(self.number)

Extra troubleshooting

Here's the sql that is being generated, it's not looking in the trench table.

queryset = Context.objects.filter(trench_id__trench_id=4)

print(queryset.query)

SELECT "kap"."context"."context_id", "kap"."context"."trench_id", "kap"."context"."number", "kap"."context"."type", "kap"."context"."description", "kap"."context"."excavation_method", "kap"."context"."open_date", "kap"."context"."close_date", "kap"."context"."excavated_by", "kap"."context"."area_easting" 
FROM "kap"."context" 
WHERE "kap"."context"."trench_id" = 4 ORDER BY "kap"."context"."number" ASC

Upvotes: 1

Views: 555

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

Looks to me like it should just be Context.objects.filter(trench_id__name=request.session.get("name")). As written, you're asking for the name attribute of the trench_id AutoField on the Trench model - which of course doesn't exist.

Upvotes: 1

Related Questions