我有一个Position
与模型相关的 ForeignKey 字段的Emplacement
模型。在Emplacement
我为Position
.
我想要实现的是,当num_position
在实例中修改字段时Emplacement
,删除与该实例相关的位置并创建新的位置。
为此,我重写了Emplacement
模型的save()
方法并检查是否num_position
已更改。
问题是Emplacement
在修改其num_position
字段后保存模型时,出现以下错误:
ValidationError: Select a valid choice. That choice is not one of the available choices.
我想这与位置的删除/重新创建有关,但我找不到原因。
怎么了?
模型.py
class Emplacement(models.Model):
num_position = models.IntegerField()
# more fields
__original_num_position = None
def __init__(self, *args, **kwargs):
super(Emplacement, self).__init__(*args, **kwargs)
self.__original_num_position = self.num_position
def save(self, *args, **kwargs):
if self.num_position != self._Emplacement__original_num_position:
# if num_position has changed, delete existing positions and recreate <num_position> positions
Position.objects.filter(emplacement=self).delete()
for i in range(self.num_position):
position = Position()
position.emplacement = self
position.number = i+1
position.save()
super(Emplacement, self).save(*args, **kwargs)
class Position(models.Model):
emplacement = models.ForeignKey(Emplacement)
number = models.IntegerField()
管理员.py
class PositionInline(admin.TabularInline):
model = Position
class EmplacementAdmin(admin.ModelAdmin):
inlines = [PositionInline]
my_site.register(Emplacement, EmplacementAdmin)
编辑
我也尝试了一个信号,但得到了同样的错误:
@receiver(post_save, sender=Emplacement)
def create_positions(sender, instance, created, **kwargs):
"""Create positions when num_position has changed."""
if instance.num_position != instance.old_num_position:
Position.objects.filter(emplacement=instance).delete()
for i in range(instance.num_position):
position = Position()
position.emplacement = instance
position.numero = i+1
position.save()