How to Make the Foreign Key Field Optional in Django Model?
Last Updated :
23 Aug, 2024
When working with the relational database, we often need to add foreign key relationships between tables. However, when working with Django, we can simply add models.ForeignKey field to a model to relate it with some other model. By default, this field will be a required field, which means we can't create a new instance of the model without filling it in.
But what if we want to make it optional at the Form, Serializer, and database level? Well, that's exactly what we will talk about in this article. We'll learn how to make a foreign key field optional in a Django model.
Create Some Model
Let's say we have a Book and an Author model, The Book model relates to the Author model via a Foreign Key Relationship.
Python
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
def __str__(self) -> str:
return self.name
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(to=Author, on_delete=models.CASCADE)
def __str__(self) -> str:
return self.title
When we try to create an instance of Book Model without passing the Author we get the following error.
Django Shell
>>> from test_app.models import Book
>>> Book.objects.create(title="Django Tutorial")
django.db.utils.IntegrityError: NOT NULL constraint failed: test_app_book.author_id
The above error indicates that the author field i.e., author_id can not be null. That is an expected behavior.
Make Foreign Key Optional at Database Level
Setting null=True
One way to make a foreign key field optional is by setting null=True in the field definition. This allows the database to store a null value for the foreign key field.
Python
# ...
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey('Author', on_delete=models.CASCADE, null=True)
In this example, the author field is a foreign key that references the Author model. By setting null=True, we allow the author field to be null, making it optional.
Note: Don't forget to run makemigrations and migrate command to apply the changes to the database.
Now, we can create a Book instance without passing the author field.
Make Foreign Key Optional at Database LevelMake Foreign Key Optional at Form or Serializer Level
Setting blank=True
Another way to make a foreign key field optional is by setting blank=True in the field definition. The blank=True allows user to pass a null value at the form and serializer levels. When performing the form or serializer validation, we don't get any error.
Python
# ...
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey('Author', on_delete=models.CASCADE, null=True, blank=True) #change
In this example, the author field is a foreign key that references the Author model is set to null=True and blank=True. By setting blank=True, we allow the author field to be blank, at the form and serializer levels.
Code Example
A complete code example that demonstrates how to make a foreign key field optional:
Python
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey('Author', on_delete=models.CASCADE, null=True, blank=True)
In this example, we define two models: Author and Book. The Book model has a foreign key field author that references the Author model. We set both null=True and blank=True to make the author field optional.
Example
When we run the following command in the terminal:
python manage.py shell
And create new instances of the Book model with and without specifying an author:
>>> from test_app.models import Book, Author
>>> gfg = Author.objects.create(name="GFG")
<Author: GFG>
>>>
>>> book_without_author = Book.objects.create(title="Django Tutorial")
>>> book_without_author
<Book: Django Tutorial>
>>> book_with_author = Book.objects.create(title="Learn Django", author=gfg)
>>> book_with_author
<Book: Learn Django>
Output
Make Foreign Key Optional at Form or Serializer Level and Database levelConclusion
In conclusion, making a foreign key field optional in Django can be easily achieved by setting `null=True` at the database level and `blank=True` at the form or serializer level. This flexibility allows developers to create instances of models without requiring a foreign key relationship to be filled in. By applying both `null=True` and `blank=True`, we ensure that the foreign key field can be left empty both in the database and during form or serializer validation, offering greater control and adaptability when working with related models.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read