Reputation: 97
What is the proper way to do reverse lookups in Django for foreign key relationships? For instance suppose i have the following 2 models.
class Songs(models.Model):
title = models.CharField(max_length=200)
artist = models.CharField(max_length=200)
genre = models.ForeignKey('Genres')
class Genres(models.Model):
genre = models.CharField(max_length=100)
If I wanted users to be able to search songs based on genre how would i do that?
For example the below is what i want to do, but i know it doesn't work because the genre column of the Songs table is an ID, not a keyword.
song = models.Songs.objects.get(genre='Jazz')
Upvotes: 5
Views: 12100
Reputation: 473813
Use the double underscore syntax to reach the genre
field in the related model:
Songs.objects.filter(genre__genre='Jazz')
For the readability purposes and consistency, consider renaming the genre
field to name
:
class Genres(models.Model):
name = models.CharField(max_length=100)
Upvotes: 16