如何排除 Django models.Model.save() 中的字段

Nar*_*asK 4 django django-models python-3.x

我有以下内容model,保存时根据以下内容计算hash_id字段pk

class MyTable(models.Model):
    something = models.CharField(max_length=255)
    reported = models.IntegerField(default=0, blank=True)
    hash_id = models.CharField(max_length=32, db_index=True, unique=True, blank=True)

    def save(self, *a, **kw):
        super().save(*a, **kw)
        self.hash_id = hash_fn(self.pk)
        super().save(*a, **kw)
Run Code Online (Sandbox Code Playgroud)

在我的其中一行中,我views有以下几行,它们应该将reported字段增加 1,但是reported由于重写的save方法而增加了 2 :

my_table_ins.reported = F('reported') + 1
my_table_ins.save()
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想要以下内容:

    def save(self, *a, **kw):
        super().save(*a, exclude=['reported'], **kw)
        self.hash_id = hash_fn(self.pk)
        super().save(*a, **kw)
Run Code Online (Sandbox Code Playgroud)

sam*_*eri 10

添加到 @martin-castro-alvarez 答案,如果您想更新除少数字段之外的所有字段,您可以执行以下操作:

fields_to_exclude = {'reported','another_field'}
# automatically populate a list with all fields, except the ones you want to exclude
fields_to_update = [f.name for f in MyTable._meta.get_fields() if f.name not in fields_to_exclude and not f.auto_created]
my_table_ins.save(update_fields=fields_to_update)
Run Code Online (Sandbox Code Playgroud)

这将在 Django>=1.8 中工作。在旧版本中,您可以使用model._meta.get_all_field_names()


小智 5

根据官方文档,您可以使用update_fields参数指定要保存的字段

my_table_ins.reported = F('reported') + 1
my_table_ins.save(update_fields=['reported', ])  # This will only save 'reported'
Run Code Online (Sandbox Code Playgroud)

该文档可在此处获得:

https://docs.djangoproject.com/en/1.11/ref/models/instances/#specifying-which-fields-to-save