Creating Objects Associated with Propper Objects in a Django Model

Suppose there are two models: Author and Book . Of course, the Book has a foreign key for the Author . There is a create view in which the user gives the author’s name and uploads a file with a list of his books.

So, I'm trying to find a better way to create a form. Right now I have:

class AddForm(ModelForm):
     books = FileField()
     class Meta:
          model = Author

     def clean_books(self):
          return [book.strip() for book in self.cleaned_data['books'].file]

The problem is where should I put the actual creation of Model Book objects ? It looks like it should be in a method save, something like:

def save(self, commit=True):
    author = super().save(commit=True)
    Book.objects.bulk_create([Book(author=author, title=book.title, ...) for book in self.cleaned_data['books']])
    return author

? commit. , , commit=False. commit ?

+4
1

. , . formet Book . django.

+1

All Articles