Relationships In Models In Django-Free Django Tutorials

I hope before reading this post you had read the other two posts on django.
1. https://padhle.com/models-in-django-free-django-tutorials/
2. More About Models In Django-Free Django Tutorials 

So in this post we will discuss about three most common types of database relationships: many-to-one, many-to-many and one-to-one.


Many-to-one relationships

many-to-one relationship can be defined by django.db.models.ForeignKey. We can use it just like it any other field type,by including it as a class attribute of our model

ForeignKey requires a class to which the model is related as a positional requirement.

For example, if a each Car model has a Manufacturer – that is a Manufacturer can make multiple cars but each Car only has one Manufacturer .We can write it as following:

from django.db import models

class Manufacturer(models.Model):
    # ...
    pass

class Car(models.Model):
    manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
    # ...

In general web developers will use the name of the model as the  name of a ForeignKey field (manufacturer in the example above) ,but it’s not required,you can use whatever you want.For example:

class Car(models.Model):
    company_that_makes_it = models.ForeignKey(
        Manufacturer,
        on_delete=models.CASCADE,
    )
    # ..

Many-to-many relationships

many-to-many relationship can be defined by ManyToManyField. We can use it just like it any other field type,by including it as a class attribute of our model.

ManyToManyField requires a class to which the model is related as a positional requirement.

For example, if a Pizza has multiple Topping objects – that is, a Topping can be on multiple pizzas and each Pizza has multiple toppings – here’s how you’d represent that:

from django.db import models

class Topping(models.Model):
    # ...
    pass

class Pizza(models.Model):
    # ...
    toppings = models.ManyToManyField(Topping)

In general web developers will take the name of a ManyToManyField  (toppings in the example above), as aplural describing the set of related model objects,again it it is not necessary.


One-to-one relationships

one-to-one relationship can be defined by OneToOneField. We can use it just like it any other field type,by including it as a class attribute of our model.

OneToOneField requires a class to which the model is related as a positional requirement.For example

from django.db import models

class Place(models.Model):
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=80)

    def __str__(self):
        return "%s the place" % self.name

class Restaurant(models.Model):
    place = models.OneToOneField(
        Place,
        on_delete=models.CASCADE,
        primary_key=True,
    )
    serves_hot_dogs = models.BooleanField(default=False)
    serves_pizza = models.BooleanField(default=False)

    def __str__(self):
        return "%s the restaurant" % self.place.name

class Waiter(models.Model):
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)

    def __str__(self):
        return "%s the waiter at %s" % (self.name, self.restaurant)

Field name restrictions

Django places only two restrictions (which are mentioned below) on model field names:

1.A field name which you are writing while writing a model in django,cannot be a Python reserved word, because that would result in a Python syntax error. For example:

class Example(models.Model):
    pass = models.IntegerField() # 'pass' is a reserved word!

2.A field name which you are writing while writing a model in django,cannot contain more than one underscore in a row, due to the way Django’s query lookup syntax works. For example:

class Example(models.Model):
    foo__bar = models.IntegerField() # 'foo__bar' has two underscores!

Meta Options

You can give your model metadata by using an inner class meta, like below:

from django.db import models

class Ox(models.Model):
    horn_length = models.IntegerField()

    class Meta:
        ordering = ["horn_length"]
        verbose_name_plural = "oxen"

So this is all about relationships in models in django and meta data class.

Leave a Comment

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