Home » One to many Relationships in Django

One to many Relationships in Django

  • by
Relationships in Django

Last Updated on November 1, 2021 by admin

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?

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *