[Fixed]-Reference multiple foreign keys in Django Model

1👍

This is the use case for Django’s ManyToManyField. Change the appropriate field on the missions:

class missions(models.Model):
    crewmembers = models.ManyToManyField('astronauts')

You can access this from the Astronaut model side like so:

jeb = astronaut.objects.get(name='Jebediah Kerman')
crewed_missions = jeb.missions_set.all()

Or from the mission side like so:

mission = missions.objects.order_by('?')[0]
crew = mission.crewmembers.all()

This creates another table in the database, in case that is somehow a problem for you.

Leave a comment