I need to create a field that count the number of registered books of each own library.
Each book is related to a library by a ForeighKey
If I register or delete a book it should update automatically in a "book_count" field related to your own library.
libraries/models.py
from django.db import models
class Libraries(models.Model):
name = models.CharField(max_length=50)
book_count = models.IntegerField(default=0)
def __str__(self):
return self.name
books/models.py
from django.db import models
from libraries.models import Libraries
class Books(models.Model):
library = models.ForeignKey(Libraries, on_delete=models.DO_NOTHING, blank=True, null=True)
book = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.book
How can I create this simple book counter in the model of each library?
from books.models import Books