_set in django

In Django, the _set attribute is used to access the reverse relation of a model field. It allows querying related objects in a reverse relationship. The _set is automatically created by Django for reverse relations when you define a ForeignKey or a OneToOneField in a model.

Here are the steps to use _set in Django:

  1. Define Models: Define the models with the ForeignKey or OneToOneField to establish a relationship.

```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) ```

  1. Create Instances: Create instances of the models and establish relationships between them.

python author = Author.objects.create(name='John Doe') book = Book.objects.create(title='Django for Beginners', author=author)

  1. Access Reverse Relation using _set: Use the _set attribute to access the reverse relation.

python # Get all books written by a specific author books_by_author = author.book_set.all()

  1. Query and Filter: Perform queries and filters on the reverse relation.

python # Get books written by a specific author and published after a certain year books_published_after_2020 = author.book_set.filter(pub_date__year__gt=2020)

  1. Use in Templates: Utilize _set in templates to display related objects.

```html

{% for book in author.book_set.all %} {{ book.title }} {% endfor %} ```

  1. Customize Related Name: Optionally, customize the related name using the related_name attribute in the ForeignKey or OneToOneField to provide a more descriptive name.

python class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')

python # Now, access the reverse relation with the custom name books_by_author = author.books.all()

These steps illustrate the process of using _set in Django to work with reverse relations and retrieve related objects in a convenient manner.