Let's say I have two models:
class Distribution(models.Model): name = models.CharField(max_length=32) class Component(models.Model): distribution = models.ForeignKey(Distribution) percentage = models.IntegerField()
And I use a simple TabularInline
to display Component
inside the Distribution
admin form:
class ComponentInline(admin.TabularInline): model = Component extra = 1 class DistributionAdmin(admin.ModelAdmin): inlines = [ComponentInline]
So, my goal is to confirm if the percentages of the entire Component
of the Distribution
sum 100 are before saving. It sounds simple, so I did:
But this will never work, because in Django all objects are saved before saving the foreign key or many other related objects, this is not a drawback, it has a reason: it cannot save the related objects first, because the object to which they are connected is not yet defined id
( id
is None
until the object is saved for the first time in the database).
I am sure that I am not the first to encounter this problem. So, is there a way to accomplish what I'm trying to do? I was thinking maybe hacking an administrator using TabularInline
or ModelAdmin
...?
source share