user3727436
user3727436

Reputation: 97

Django queryset foreign key

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

Answers (1)

alecxe
alecxe

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

Related Questions