Open In App

How to Make the Foreign Key Field Optional in Django Model?

Last Updated : 23 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Screenshot-2024-08-22-103706
Make Foreign Key Optional at Database Level

Make 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

Screenshot-2024-08-22-105450
Make Foreign Key Optional at Form or Serializer Level and Database level

Conclusion

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.


Next Article
Practice Tags :

Similar Reads