Search code examples
pythondjangoforeign-keysmany-to-many

django - using of related_name in ManyToMany and in ForeignKey


I have two models (and also using the auth.user). the auth.user and the Ride model have two relations between them, and the Ride model and Destination model have two relations between them.

The Ride has many middle destinations and one final destination. The Ride has many passengers and one driver.

class Destination(models.Model):
    name=models.CharField(max_length=30)

class Ride(models.Model):
    driver = models.ForeignKey('auth.User', related_name='rides_as_driver')
    destination=models.ForeignKey(Destination)
    leaving_time=models.DateTimeField()
    num_of_spots=models.IntegerField()
    passengers=models.ManyToManyField('auth.User', related_name="rides_as_passenger")
    mid_destinations=models.ManyToManyField(Destination)

I am trying to fully understand what is the meaning of the related_name attribute. I read a lot about it but still not sure...

Also I read that if I have two relations between to models, I have to use the related_name.

Can someone explain to me:

  • What exactly is the related_name attribute? When do I use it?
  • When and Where will I be using the rides_as_driver and rides_as_passenger?
  • What should I put in the fields with the Destination? (middle destinations and final destination)?

Thanks a lot!


Solution

  • As the name implies, this is the name you use when accessing the model from the related one. So, if you had a user instance, my_user.rides_as_driver.all() would give you all the Rides where ride.driver == my_user, and my_user.rides_as_passenger.all() would give you all the Rides where ride.passengers contains my_user.