django related_name abstract class
from django.db import models
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Author(BaseModel):
name = models.CharField(max_length=100)
class Book(BaseModel):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
Import the
models
module fromdjango.db
.Define an abstract base model class called
BaseModel
that inherits frommodels.Model
.Add two fields,
created_at
andupdated_at
, to theBaseModel
class. Usemodels.DateTimeField
withauto_now_add=True
forcreated_at
andauto_now=True
forupdated_at
.Set
class Meta
withinBaseModel
and set theabstract
attribute toTrue
. This makes theBaseModel
an abstract class, meaning it won't create a database table for itself.Define a new model class called
Author
that inherits fromBaseModel
. Add aname
field usingmodels.CharField
withmax_length=100
.Define another model class called
Book
that also inherits fromBaseModel
. Add atitle
field usingmodels.CharField
withmax_length=200
.Create a foreign key relationship in the
Book
model, linking it to theAuthor
model. Usemodels.ForeignKey
withon_delete=models.CASCADE
to specify that if an author is deleted, all associated books should be deleted as well. Also, setrelated_name='books'
to define the reverse relation fromAuthor
toBook
.
These steps result in two models, Author
and Book
, with a one-to-many relationship between them. The related_name='books'
allows you to access the set of books associated with an author using the books
attribute.