Field
An attribute within a Model class used to track a characteristic of the data.
Definition: CharField
A string.
name = models.CharField(max_length=255)
Definition: TextField
A long string.
quote = models.TextField()
ForeignKey
One-to-Many.
class BookQuote(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='quotes')
Workflow: Implement One-to-Many
Add
models.ForeignKey(Book).Add
on_deleteandrelated_name.class Book(models.Model): name = models.CharField(max_length=255) class BookQuote(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='quotes')
Access data:
from
BookQuote:quote = BookQuote.objects.get(id=1) parent_book = quote.book
from
Book:book = Book.objects.get(id=1) all_quotes = book.quotes.all()
Save data:
new_quote = BookQuote(content="To be or not to be", book=book_instance) new_quote.save()
ManyToManyField
A field used to create a relationship where multiple records in one table can be associated with multiple records in another table.
Workflow: Many-to-Many
Add
models.ManyToManyField(Author).Add
related_name.class Author(models.Model): name = models.CharField(max_length=255) class Book(models.Model): title = models.CharField(max_length=255) authors = models.ManyToManyField(Author, related_name='books')
Access data:
from
Book:book = Book.objects.get(id=1) book_authors = book.authors.all() book.authors.add(author_instance)
from
Author:author = Author.objects.get(id=1) author_books = author.books.all()
Save data:
book.authors.add(author_instance) book.authors.set([author1, author2])