我有一個與其他兩個模型(ItemComponent 和或 ItemComponentCategory)反向相關的 Item 模型。這個想法是我希望能夠在保存之前驗證專案與其他兩個模型的關系不超過 4 個。
class Item(models.Model):
name = models.CharField(max_length=40, unique=True)
class ItemComponent(models.Model):
parent_item = models.ForeignKey(Item, related_name='components')
class ItemComponentCategory(models.Model):
parent_item = models.ForeignKey(Item, related_name='categories')
如果保存的物件將導致它們之間有 > 4 個物件關系,我想創建一個在保存 Item、ItemComponent 或 ItemComponentCategory 物件之前引發錯誤的驗證。
我已經嘗試將這樣的東西添加到所有三個的干凈方法中:
def clean(self):
if (self.parent_item.components.count() self.parent_item.categories.count()) > 4:
raise ValidationError(_(f'Items can have no more than 4 components and/or component categories'))
只要 Items 及其關系已經用 4 保存并且您嘗試添加更多關系,這似乎就可以作業。
但是,如果我在 ItemAdmin 中創建一個 TabularInline 來添加這些“子型別”,如果您愿意的話……我可以創建一個新專案并添加盡可能多的這些子型別并保存它沒有問題。
我在這里錯過了什么?
uj5u.com熱心網友回復:
我的問題似乎與流程的時間和順序有關。
使用行內參考保存管理頁面時,首先保存主頁的模型,然后保存行內物件。當嘗試使用模型的 clean() 方法來驗證關系時,這會帶來一個問題,因為它根本不存在。
正如在提到本文章看來,我的解決辦法是修改的ModelAdmin功能,以確保聯物件首先被保存,然后他們得救后驗證的主要物件。
另外,我認為modelAdmin的這個save_related方法會派上用場。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/401804.html
