您可以在不调用save()的情况下更新模型实例吗?

时间:2018-12-12 22:58:38

标签: python django django-models model

我正在从事一个需要独特弹头的项目。这些弹头是使用对象名称在自定义save()方法中动态创建的。

class SlugMixin(models.Model):
    def save(self, *args, **kwargs):
        slug = striptags(self.name)
        self.slug = slugify(slug)
        super(SlugMixin, self).save(*args, **kwargs)

    class Meta:
        abstract = True

名称不是唯一的,因此可能有多个相同的子段。因此,我正在使用的解决方案是将实例的ID附加到post_save中的子对象中。这里的问题是通过尝试使用ID更新该段。 save()需要再次调用。

def ensure_unique_slug(sender, instance, created, **kwargs):
    if created and Person.objects.filter(slug=instance.slug).count() > 1:
        instance.slug = instance.slug + '-{}'.format(instance.id)
        instance.save()

使更新无效。无论如何有没有调用save()来更新子弹

0 个答案:

没有答案
相关问题