python - 是否可以从 Django 信号中的请求访问非数据库 key ?

标签 python django django-rest-framework

我正在执行 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/

相关文章:

python - 如何从列表中的元素中删除括号 (Python)

python - Python 2.7 (win 32) 中没有名为 pygtk 的模块,但它肯定已安装

python - 如何在 django 翻译中保留内联链接?

python - Django Rest框架属性错误

python - Django Rest Framework 中的 APITestCase、APISImpleTestCase 和 APITransactionTestCase 有哪些不同的用例

python - 在 python 中将错误从类传递到渲染的 html 的正确方法是什么

使用新数据框更新 Python Dash 应用程序

python - Django ORM : How to query for the latest row based on a another attribute

django - AttributeError : type object 'User' has no attribute 'name'

python - 从 xml 生成 django 模型