重写save方法会在创建对象时引发异常

2024-06-02 06:20:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为我的调度程序模型创建一个标识器,它依赖于这个模型的ManyToManyField

问题是,当我重写save方法时,第一次(创建对象时)它会导致问题。应该先保存。另一方面,当我创建一个post_save信号时,问题是我必须save这个信号中以infi结尾的模型

class Scheduler(models.Model):
    weekhours = models.ManyToManyField('WeekHour', related_name='schedulers')
    identificator = models.TextField(null=True,blank=True)

    def save(self,*args,**kwargs):
        if self.weekhours.all():
            identificator = ','.join([str(x.hour) for x in self.weekhours.all().order_by('hour')])
            self.identificator = identificator
        super(Scheduler, self).save(*args, **kwargs)

ValueError: "<Scheduler: None>" needs to have a value for field "scheduler" before this many-to-many relationship can be used.

你有什么想法吗


Tags: 模型selftruefor信号modelssaveargs
1条回答
网友
1楼 · 发布于 2024-06-02 06:20:26

嗯,那你呢

# some logic here (count the identificator)
objects.filter(id=my_id).update(identificator=identificator)

在您的信号中-并且不要覆盖保存?:)

相关问题 更多 >