One to many Relationships in Django

Share This Post

In one to many relationships Django, one record the linked with another record.

If you know the object-oriented programming, one to one relationship in Relational Database Management System is like object-oriented endowment which uses the is a rule

(eg. Mobile phone is a device).

Such as, general item model records can have a one-to-one relationship with the drink item model.

On the other hand, the latter records hold the information about drink items and the former record holds the information about general items.

The one-to-one field data type is used to define the one-to-one relationship in Django. The example that defines the one to one relationship is as follows:

One to many Relationships Django models

class Menu(models.Model):

name = models.CharField(max_length=30)

class Item(models.Model):

menu = models.ForeignKey(Menu)

name = models.CharField(max_length=30)

description = models.CharField(max_length=100)

calories = models.IntegerField()

price = models.FloatField()

class Drink(models.Model):

item = models.OneToOneField(Item,on_delete=models.CASCADE,primary_key=True)

caffeine = models.IntegerField()

The first Django model in this listing is Item and this model has additional Calories and price fields.

The next model in this listing is the drink model which is also in the item field which is also a model itself.

Options for relationship model data types

The are many options in relationship model types which are as follows:

  • Data rectitude options

(It works  on_delete )

  • Reference options

(This related to self-referencing model)

  • Reverse relationships

(This establishes the reverse relationship between the set models )

  • Database options

(The field stores the id from the menu)

  • Form Values

(Relationships are used in the contexts of the forum)

Read More: How to Join Words in List Python?


Related Posts

Python for Loop Iteration: How to Easily Manipulate a List

One of the most powerful features of the Python...

How To Get First Characters of a String in Python

Way to find the first characters of a string...

How To Convert Tuple To String In Python

In this post, you will learn how to convert...

How To Convert String to Double in Python

Good to hear, that you want to convert a...

Python TypeError: String Index Out Of Range Solution

A string is an array of characters and part...

How To Remove Empty Strings From a List Of Strings

On this page, we will discuss how to remove...
- Advertisement -spot_img