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
How to Make Many-to-Many Field Optional in Django
In Django, many-to-many relationships are used when a model can have relationships with multiple instances of another model and vice versa. For example, a book can have many authors, and an author can have written many books. To handle these kinds of relationships, Django provides the ManyToManyFiel
5 min read
How to Get a List of the Fields in a Django Model
When working with Django models, it's often necessary to access the fields of a model dynamically. For instance, we might want to loop through the fields or display them in a form without manually specifying each one. Django provides a simple way to get this information using model meta options. Eac
2 min read
Foreign Keys On_Delete Option in Django Models
In Django models, the on_delete option is used to specify the behavior that should be taken when the referenced object (usually a foreign key target) is deleted. This option is crucial for maintaining data integrity and handling relationships between models. The on_delete option is required when you
3 min read
How to Filter ForeignKey Choices in a Django ModelForm
A ForeignKey field allows one model to relate to another in Django. When this field is represented in a form (e.g., a Django ModelForm), it typically displays a dropdown list (a select box) populated with all the objects from the related model. However, there are many scenarios where we may need to
7 min read
Intermediate fields in Django | Python
Prerequisite: Django models, Relational fields in DjangoIn Django, a many-to-many relationship exists between two models A and B, when one instance of A is related to multiple instances of B, and vice versa. For example - In a shop management system, an Item and a Customer share a many-to-many relat
2 min read
Python | Relational fields in Django models
Prerequisite: Django models Django models represent real-world entities, and it is rarely the case that real-world entities are entirely independent of each other. Hence Django supports relational databases and allows us to establish relations between different models. There are three types of relat
4 min read
How to Express a One-To-Many Relationship in Django?
In Django, expressing relationships between models is crucial to structuring our database. One of the most common relationships is One-To-Many, where a single record in one model is associated with multiple records in another model. For example, an author can write multiple books, but each book is w
5 min read
How to Change Field Name in Django REST Framework Serializer
When working with Django REST Framework (DRF), we may encounter situations where we need to change the name of a field in a serializer. This can be useful when we want to expose a model field with a different name in our API or when we need to conform to a specific API schema. In this article, we wi
3 min read
Include Related Model Fields In Django Rest Framework
In Django Rest Framework (DRF), it is common to work with related models, especially when building APIs that expose complex data structures. We might need to include data from related models (like foreign keys and many-to-many relationships) in our serialized API responses. DRF provides powerful mec
3 min read
How to Extend User Model in Django
Djangoâs built-in User model is useful, but it may not always meet your requirements. Fortunately, Django provides a way to extend the User model to add additional fields and methods. In this article, we'll walk through the process of extending the User model by creating a small web project that dis
3 min read