_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:
- 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) ```
- 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)
- 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()
- 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)
- Use in Templates:
Utilize
_set
in templates to display related objects.
```html
{% for book in author.book_set.all %} {{ book.title }} {% endfor %} ```
- 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.