Question

models:

class Book(models.Model):
    name = models.Char()

class BookCount(models.Model):
    book = OneToOneField(Book)
    count = SmallIntegerField(default=0)

views:

class BookCreate(CreateView):
    model = Application

The question is, after create Book, I want insert a record to BookCount. Any ideas?

Was it helpful?

Solution

If your BookCount model is required you could use a listener for the post_save signal along the lines of this:

# models.py

from django.db.models.signals import post_save

# Model definitions
...

def create_book_count(sender, instance, created, **kwargs):
    if created:
        BookCount.objects.create(book=instance)

post_save.connect(create_book_count, sender=Book)

If your models are really this simple, you may want to drop the BookCount model and add a count field to your Book model instead to reduce the complexity and overhead here. See the docs on extending the user model for a short overview of why it might be better to avoid the OneToOneField option (the wording is specific to the User model, but it applies here, too):

Note that using related models results in additional queries or joins to retrieve the related data, and depending on your needs substituting the User model and adding the related fields may be your better option. However existing links to the default User model within your project’s apps may justify the extra database load.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top