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:
Thanks a lot!
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
.