我正在执行 API 请求,并随请求发送非数据库 key 。
在 Django 的预信号中,我想使用该键来做出决定。
可以吗?如果是的话我该怎么做?
示例场景:
# POST request body from postman
{
"field1": 10,
"custom_field": True
}
# test model
class TestModel(models.Model):
field1 = model.IntegerField(default=0)
field2 = model.CharField(default="test")
# django pre save signal
pre_save.connect(test_function, sender=TestModel)
# test function in some helper
def test_function(sender, instance, raw, using,
update_fields, **extra_fields):
# here I'm using the custom field which is not in model
if instance.custom_field:
instance.field2 = "hello"
else:
instance.field2 = "hi"
我收到错误,即AttributeError:“ModelTest”对象没有属性“custom_field”
希望你能理解。
提前致谢。
最佳答案
您可以在 .save()
方法中传递参数。
类似这样的:product.save(update_fields=['name'])
注意:您不必仅传递模型字段。
引用:https://docs.djangoproject.com/en/2.2/ref/models/instances/#specifying-which-fields-to-save
关于python - 是否可以从 Django 信号中的请求访问非数据库 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57788928/