在Django中,如何仅在字段具有已知值时才保存对象

时间:2021-09-18 20:28:43

In Django, I would like to do a save of an object only if a given field has a known value, otherwise I would like to get an exception.

在Django中,我只想在给定字段具有已知值的情况下保存对象,否则我想获得异常。

Is there some other way then doing it manually, locking the table (or row, with Django 1.4 SELECT FOR UPDATE support) before saving, reading the value, checking, and if they match, saving, otherwise throwing an exception?

还有其他方法然后手动执行,锁定表(或行,使用Django 1.4 SELECT FOR UPDATE支持),然后保存,读取值,检查,如果它们匹配,保存,否则抛出异常?

In SQL I could do something like:

在SQL中我可以做类似的事情:

UPDATE table SET field='value' WHERE id=42 AND given_field='known_value'

and checking how many rows were updated.

并检查更新了多少行。

2 个解决方案

#1


1  

You can place your validation code in save method, for example.

例如,您可以将验证代码放在save方法中。

from django.core.exceptions import ValidationError

class YourModel(models.Model):
    # fields

    def save(self, *args, **kwargs):
        if self.given_field == 'known_value':
            raise ValidationError(u"You can't do that!")
        super(YourModel, self).save(*args, **kwargs)

The only things here is that 1) you won't get this validation if using bulk update and 2) this validation will break in admin

这里唯一的事情是:1)如果使用批量更新,您将无法获得此验证; 2)此验证将在管理中断开

(2) is solved if you move your validation to model's clean method.

如果将验证移到模型的清洁方法,则解决了(2)。

#2


0  

Use queryset's update() method:

使用queryset的update()方法:

obj_data = dict((field.name, getattr(obj, field.name))
                    for field in obj._meta.fields)

rows_affected = MyModel.objects.filter(
                   id=obj.id, given_field='known_value').update(**obj_data)

#1


1  

You can place your validation code in save method, for example.

例如,您可以将验证代码放在save方法中。

from django.core.exceptions import ValidationError

class YourModel(models.Model):
    # fields

    def save(self, *args, **kwargs):
        if self.given_field == 'known_value':
            raise ValidationError(u"You can't do that!")
        super(YourModel, self).save(*args, **kwargs)

The only things here is that 1) you won't get this validation if using bulk update and 2) this validation will break in admin

这里唯一的事情是:1)如果使用批量更新,您将无法获得此验证; 2)此验证将在管理中断开

(2) is solved if you move your validation to model's clean method.

如果将验证移到模型的清洁方法,则解决了(2)。

#2


0  

Use queryset's update() method:

使用queryset的update()方法:

obj_data = dict((field.name, getattr(obj, field.name))
                    for field in obj._meta.fields)

rows_affected = MyModel.objects.filter(
                   id=obj.id, given_field='known_value').update(**obj_data)