OneToOneField in Django Model | related_name Example

OneToOneField in Django Model | related_name Example

In this tutorial, I’m explaining the OneToOneField relationship in the Django model and how to access these model fields in the Django template using related_name.

Django supports both OneToOneField and ForeignKey fields. Both are different concepts. For the foreign key, follow this tutorial.

Let’s get into the practical example where we are setting up the OneToOneField relationship in Django model.

OneToOneField Relationship in Django Model

Suppose you have this model called Author.

class Author(models.Model):
    author_name = models.CharField(max_length=120)

Now, you want to create another model which will have a one-to-one relation with the model ‘Author’, says ‘Contact’.

Use the ‘OneToOneField‘ model attribute as below.

class Contact(models.Model):
 	author = models.OneToOneField(User, on_delete=models.CASCADE, related_name="author_contact")
    address = models.CharField(max_length=120)
    mobile = models.IntegerField(blank=True, null=True)

Look at the above code, we are using related_name. This can be considered as one of the Django related name examples.

Note: If you are making any changes to the, make sure you do the complete migrations.

Accessing OneToOneField Model fields in Django Templates

Now we are reading all the contacts and also reading the name of the author for each contact.

Get all the objects of the model ‘Contact’ in your file.

contact = Contact.objects.filter()

And pass this to the template.

Now, go to your HTML template and add this code.

{% conatct for contacts %}
{% endfor %}

This will show the list of all the contacts including the author’s name.

It’s simple. Isn’t it?

Now, what if you want to get the user contact details for each user?

Reverse Look Up (aka Backward Compatibility)

Python also supports backward compatibility. It is also called reverse compatibility.

Get all the objects of the model ‘Author’ in your file.

authors = Author.objects.filter()

Here are using a related_name ‘author_contact’ that we set in the ‘Contact’ Django model.

{% auth for authors %}
{% endfor %}

Look, guys. I tried to keep this tutorial easy to refer. Hope you find it useful. If you have any questions, let me know in the comment below. Thanks!

Leave a Reply

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