I've read many posts on what OneToOneField, ManyToManyField, and Foreign Key are but they aren't very clear. I am very new to Django and python programming, currently trying to develop models. Can someone explain to me in simple language, preferably with example, what they each are?
A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True , but the "reverse" side of the relation will directly return a single object. In contrast to the OneToOneField "reverse" relation, a ForeignKey "reverse" relation returns a QuerySet .
The Foreign key allows the match between a primary key of a different table. From the kind of relationship generated the foreign key field will allow many to one relationship. so more than one tables could be flexibly connected with one table on the other end.
This is used when one record of a model A is related to exactly one record of another model B. This field can be useful as a primary key of an object if that object extends another object in some way. For example – a model Car has one-to-one relationship with a model Vehicle, i.e. a car is a vehicle.
To define a many-to-one relationship, use ForeignKey . What follows are examples of operations that can be performed using the Python API facilities. Note that you must save an object before it can be assigned to a foreign key relationship.
Imagine a database, which stores your book collection:
from django.db import models
class Place(models.Model):
address = models.CharField(max_length=50)
country = models.CharField(max_length=50)
class Publisher(models.Model):
name = models.CharField(max_length=30)
place = models.OneToOneField(Place, primary_key=True)
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
class Book(models.Model):
title = models.CharField(max_length=100)
publisher = models.ForeignKey(Publisher)
authors = models.ManyToManyField(Author)
One-to-many/Foreign Key
Every Book
has one Publisher
, but a Publisher
might have published multiple books. Therefore they are in a one-to-many (book-to-publisher) relationship.
One-to-one
Every Publisher
is located in one Place
, and every Place
can only hold one Publisher
. Therefore they are in a one-to-one relationship. You could just have well have put the Place
information (address
and country
) with the Publisher
model in one table, but sometimes it is preferred to have seperate models. For example, if you do not know the Place
for every Publisher
, you don't need to take up a lot of space with empty rows.
Many-to-many
Every Book
also has one or more Author
s. However, an Author
might have written multiple Book
s, so they are in a many-to-many relationship.
If you still need some guidance, I suggest taking a look at the model chapter of the Django Book.
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