How to save OneToMany in Django Admin
This is my models
class Author(models.Model):
full_name = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.full_name
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE, db_column='author_id',related_name='authors',null=True,blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
My admin setup
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
list_display = ('id', 'full_name', 'created_at', 'updated_at')
search_fields = ['full_name']
ordering = ['-created_at']
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'author', 'created_at', 'updated_at')
search_fields = ['title']
list_filter = ['author__full_name']
ordering = ['-created_at']
I want from create Author page. I can select multiple Book
with author_id = Null
. And when i save it, it will update author_id
for all selected Book
Please help me
You can use TabularInline
class (https://docs.djangoproject.com/en/5.0/ref/contrib/admin/#working-with-many-to-many-models). It is describing for M2M relation but it can be applied for reverse foreign key too
class BookInline(admin.TabularInline):
model = Author.authors.through # to fix after change the related_name property
extra = 0
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
list_display = ('id', 'full_name', 'created_at', 'updated_at')
search_fields = ['full_name']
ordering = ['-created_at']
inlines = [
BookInline,
]
For information, the related_name
property in ForeignKey
is the name of the property for the other class to access to this Model, so in your case, the related_name
of the Book model should be books