Ofek Agmon
Ofek Agmon

Reputation: 5198

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

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

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?

Upvotes: 2

Views: 671

Answers (2)

Danial Tz
Danial Tz

Reputation: 1984

what you want is probably something like this

class MyModel(models.Model):

    driver = models.ForeignKey(to=User, related_name='r_driver')
    # you need to use a related name if you want to link to the same model more than once
    passengers = models.ManyToManyField(User, related_name="r_passengers")

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599490

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.

Upvotes: 1

Related Questions