Search code examples
djangodatabasemany-to-manymany-to-one

django - many-to-many and one-to-many relationships


I am working in django, am planning a database for rides for users.

  • each User can be on multiple Rides (over time) and each Ride can have multiple Users (passengers) in it.

  • Also, for each Ride there has to be only one Driver (also a User) so I think I have a many-to many relationship between the Rides and Users tables for what user is on what ride, and also a One-To-Many relationship between the Rides's Driver_id and the User_id. right?

My questions are-

  1. I saw in the django docs that I should put a many-to-many field in One of the models. Does it matter which one? and also, does it create a new table like rides_users?

  2. and also, what is the difference (in One-To-many relationship) between using a foreignKey field and a OneToManyField field?

EDIT:

Currently, there are my models:

def get_image_path(models.Model):
    return os.path.join('photos',str(instance.id),filename)


class UserProfile(models.Model):
    user=models.OneToOneField(User)
    phone_number=models.CharField(max_length=12)
    profile_picture=models.ImageField(upload_to=get_image_path, black=True, null=True)

class Ride(models.Model):
    driver=models.ForeignKey(UserProfile, related_name="r_driver")
    destination=models.ForeignKey(Destination, related_name="r_final_destination")
    leaving_time=models.DateTimeField()
    num_of_spots=models.IntergerField()
    passengers=models.ManyToMany(UserProfile, related_name="r_passengers")
    mid_destinations=models.ManyToMany(Destination, related_name="r_mid_destinations")

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

As you can see, each Ride has multiple mid_destination and multiple passengers. a Ride also has One driver and One final destination.

The Issue is - when a User adds a Ride, I want the driver, destination and mid_destinations and the rest of the fields to be set by the User (the driver is user adding the Ride), Except for the passengers field. I want the other Users to add themselves to the ride, so when the Ride is created the User (driver) doesn't have to set the passengers.

How do I go about it? and also, any other suggestions about the models?


Solution

  • There is no such thing as a OneToManyField.

    It doesn't matter from a practical point of view which side the ManyToManyField lives on. Personally, I'd put it on Ride, both to avoid changing the User model and because conceptually I'd say that rides are the main objects here.

    And yes, adding the field will automatically create the linking table.