Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 699
Ofek Agmon Avatar asked May 22 '15 10:05

Ofek Agmon


People also ask

What is the use of Related_name in Django models?

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.

How do you implement many-to-many relationships in Django?

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.

How do you use many-to-many fields?

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.

How do I create a one to many relationship in Django?

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).


1 Answers

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.

like image 99
Daniel Roseman Avatar answered Sep 20 '22 12:09

Daniel Roseman