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!
The related_name attribute specifies the name of the reverse relation from the User model back to your model. If you don't specify a related_name, Django automatically creates one using the name of your model with the suffix _set.
To define a many-to-many relationship, use ManyToManyField . What follows are examples of operations that can be performed using the Python API facilities. You can't associate it with a Publication until it's been saved: >>> a1.
A ManyToMany field is used when a model needs to reference multiple instances of another model. Use cases include: A user needs to assign multiple categories to a blog post. A user wants to add multiple blog posts to a publication.
To handle One-To-Many relationships in Django you need to use ForeignKey . The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With