How to create a Django model with a ForeignKey and related_name



Image not found!!


To create a Django model with a ForeignKey and related_name, you need to define the ForeignKey field in your model class and specify the related_name parameter. Here's an example of how to do this:

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=100) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books') # In this example, the related_name parameter is set to 'books', which allows you to access the related Book objects from an Author instance using the 'books' attribute.

In the above example:

  • We define two model classes: Author and Book.
  • The Book model has a ForeignKey field named author that points to the Author model. The on_delete=models.CASCADE parameter specifies that when an Author instance is deleted, all associated Book instances should be deleted as well.
  • The related_name parameter is set to 'books', which means you can access the related Book objects from an Author instance using the books attribute. For example: author_instance.books.all() will give you all the books written by that author.

Remember to run python manage.py makemigrations and python manage.py migrate after defining your models to create the corresponding database tables.