values django
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
birth_date = models.DateField()
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
publication_date = models.DateField()
def __str__(self):
return self.title
Explanation:
- The code imports necessary modules from Django (
models
). - Two models are defined:
Author
andBook
. Author
model has two fields:name
(a character field with a maximum length of 100) andbirth_date
(a date field).Book
model has three fields:title
(a character field with a maximum length of 200),author
(a foreign key relating to theAuthor
model with a "one-to-many" relationship usingForeignKey
), andpublication_date
(a date field).- The
__str__
method is defined in both models to provide a human-readable representation of the objects when printed or displayed. Author
andBook
are Django models that represent tables in the database, allowing data to be stored and manipulated using Django's ORM (Object-Relational Mapping).ForeignKey
establishes a relationship between theBook
andAuthor
models, indicating that each book is associated with an author, and theon_delete=models.CASCADE
argument ensures that if anAuthor
instance is deleted, all relatedBook
instances associated with that author will also be deleted (CASCADE
behavior).
This code snippet illustrates a basic example of defining models in Django for a simple library application, showcasing relationships between authors and books through Django's ORM.