Django: Many-to-One Relationship

Today we are gone to talk about the Foreign Key which is used to establish a many-to-one relationship and different args which can be passed.

Syntax to define a Foreign key relationship

from django.db import models

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

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE)

Different args for the Foreign Key

on_delete This args handle the process, of what to do if the reference keys are deleted, we have three options – CASCADE: It deletes the objects contains the Foreign key – PROTECT: It prevents the deletion of the referenced object by raising ProtectedError – RESTRICT: Introduced in Django 3.1, It only deletes the object, if another references object is being deleted in the same operation, but with CASCADE flow otherwise raise RestrictedError

from django.db import models

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

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE)

limit_choices_to This is helpful in the form rendering to restrict the option for the reference field. The limited choice can either be a dict, Q object or a callable that return dict or Q object

from django.db import models

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

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE, limit_choices_to={'tax_type': 'gst'},)
# here we only show the tax of type GST only.

related_name It's the name that can be used for the reverse or backward reference while querying. You can also stop the backward relation by assigning + in related_name.


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

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE, related_name='+',) # IN this case GSTRate cannot backward realte to the Purchase Order obejct.

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE, related_name='invoice')

# here you can refer to Invoice inside GSTRate query by the related name.
GSTRate.objects.filter(invoice_id=1232)

related_query_name It has the same value as the related_name, unless not specified explicitly. If it is defined then you have to use that name while querying


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

class OrderConfirmation(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE, related_name='order_confirmation', related_query_name='oc')

# here you can refer to Invoice inside GSTRate query by the related name.
GSTRate.objects.filter(oc_id=112)

to_field This is helpful in the case where you want to refer other the primary key of the modal, but the condition whatever key you referred it should be unique=True

db_constraints This is used to create a constraint at the database level, by default value is true and if the user sets the value to False, then accessing a related object that doesn’t exist will raise its DoesNotExist exception.

Conclusion These args are handy which gives us the possibilities of implementing the additional constraint and functionality to query data in the Django ORM query language.

Cheers!

#100DaysToOffload #Python#Django