Number模型是没有表的假模型,我不应该保存它。我需要的是将所有内联Number.number保存为Message.receiver。 但是save_model首先调用并在保存Message cals之后保存刚刚传递的Number。我需要从Number内联模型访问父消息模型。 我试图从NumberAdmin重载save_model(),但没有成功。 我知道什么设计是坏的,但它是遗产。
models.py
class Message(models.Model):
receiver = models.BigIntegerField()
text = models.TextField(blank=True, null=True)
class Meta:
db_table = 'messages'
def __str__(self):
return "{}".format(self.text)
class Number(models.Model):
message = models.ForeignKey("Message", related_name='receivers')
number = models.BigIntegerField()
class Meta:
verbose_name = "ReceiverNumber"
verbose_name_plural = "ReceiverNumbers"
managed = False
def __str__(self):
return self.number
admin.py
class NumberInline(admin.TabularInline):
model = Number
extra = 0
fields = ('number',)
class NumberAdmin(admin.ModelAdmin):
class Meta:
model = Number
class MessageAdmin(admin.ModelAdmin):
inlines = (ReceiverNumberInline,)
class Meta:
model = Message
答案 0 :(得分:0)
我不确定我是否完全理解这个问题,但您是否尝试覆盖save
模型的Number
方法?
class Number(models.Model):
message = models.ForeignKey("Message", related_name='receivers')
number = models.BigIntegerField()
class Meta:
verbose_name = "ReceiverNumber"
verbose_name_plural = "ReceiverNumbers"
managed = False
def __str__(self):
return self.number
def save(self, *args, **kwargs):
# do whatever you need without invoking super().save()