我有两个模型:
class Author(models.Model):
name = models.CharField(max_length=100)
create_report = models.BooleanField(default=False)
class Book(models.Model):
author = models.ForeignKey(Author, on_delete=models.PROTECT)
title = models.CharField(max_length=100)
它们在管理员中注册如下:
class BookInline(admin.TabularInline):
model = PurchaseOrderItem
@admin.register(PurchaseOrder)
class AuthorAdmin(admin.ModelAdmin):
inlines = (PurchaseOrderInline,)
我通过 Django 管理创建了一位作者和两本书。点击“保存”按钮后,如果 Author.create_report == True
我希望看到一份报告,内容如下:
Author Whoever-he-is has written the following books:
Title-of-the-first-book
Title-of-the-first-book
(报告应在何处显示或如何呈现模板与此处无关,让我们跳过它们。)
我的第一个想法是覆盖 Author.save()
方法:
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
if self.create_report:
self.write_report(name=self.name, books=self.book_set.all())
问题在于 Author.save()
方法在保存 Book
对象之前执行,因此 self.book_set.all()
为空。
一种解决方法是使用其他一些 ModelAdmin
函数(例如 log_addition()
),该函数在保存 Book
对象后触发,但由于我也希望在管理之外使用相同的功能,所以这不是最好的解决方案。
我可以在不使用管理层功能的情况下以某种方式实现结果吗?
最佳答案
book_set.all()
最初将为 Null
,因为没有与 Author
相关的 Book
> 在作者创作时。因此,我的建议是,在创建图书
时生成报告。
class Author(models.Model):
name = models.CharField(max_length=100)
create_report = models.BooleanField(default=False)
class Book(models.Model):
author = models.ForeignKey(<b>Author</b>, on_delete=models.PROTECT)
title = models.CharField(max_length=100)
<b>def save(self, *args, **kwargs):
pk = self.pk # pk will be None like objects if self is new instance
super().save(*args, **kwargs)
if not pk and self.author.create_report:
write_report(name=self.author.name, books=self.author.book_set.all())</b>
关于python - Django:保存相关对象后执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51548069/