ChrisM
ChrisM

Reputation: 2248

Django - get object based on ForeignKey field

I need to get a single model object based on a set of fields one of which is a ForeignKey. So if I have the following models:

class Composer(models.Model):
    name = models.CharField()
    dates =  models.CharField()
    nationality = models.CharField()
    period = models.CharField()

class Symphony(models.Model):
    composer = models.ForeignKey('Composer', related_name="symphonies", null=True)
    date = models.CharField()
    key = models.CharField()
    number = models.IntegerField()
    num_movements = models.IntegerField()

how can I then retrieve a specific Symphony object based on its composer and number fields? I originally had composer as a simple models.CharField(), so I could just do:

Symphony.objects.get(composer='Bruckner', number=7)

So how do I do the equivalent using a ForeignKey?

Upvotes: 1

Views: 3073

Answers (1)

Gocht
Gocht

Reputation: 10256

This should work, but you should always use a unique value:

Symphony.objects.get(composer__name='Bruckner', number=7)

Here you can find more usages for double underscore notation (__)

Upvotes: 6

Related Questions