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')
  1. Import the models module from django.db.

  2. Define an abstract base model class called BaseModel that inherits from models.Model.

  3. Add two fields, created_at and updated_at, to the BaseModel class. Use models.DateTimeField with auto_now_add=True for created_at and auto_now=True for updated_at.

  4. Set class Meta within BaseModel and set the abstract attribute to True. This makes the BaseModel an abstract class, meaning it won't create a database table for itself.

  5. Define a new model class called Author that inherits from BaseModel. Add a name field using models.CharField with max_length=100.

  6. Define another model class called Book that also inherits from BaseModel. Add a title field using models.CharField with max_length=200.

  7. Create a foreign key relationship in the Book model, linking it to the Author model. Use models.ForeignKey with on_delete=models.CASCADE to specify that if an author is deleted, all associated books should be deleted as well. Also, set related_name='books' to define the reverse relation from Author to Book.

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.