Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用peewee更新动态确定的字段_Python_Mysql_Peewee - Fatal编程技术网

Python 使用peewee更新动态确定的字段

Python 使用peewee更新动态确定的字段,python,mysql,peewee,Python,Mysql,Peewee,我有一个peewee模型,如下所示: class Parrot(Model): is_alive = BooleanField() bought = DateField() color = CharField() name = CharField() id = IntegerField() 我从用户那里获取这些数据,并在(MySQL)数据库中查找相应的id。我现在要做的是更新那些当前未设置/为空的属性。例如,如果新数据具有以下属性: is_alive =

我有一个peewee模型,如下所示:

class Parrot(Model):
    is_alive = BooleanField()
    bought = DateField()
    color = CharField()
    name = CharField()
    id = IntegerField()
我从用户那里获取这些数据,并在(MySQL)数据库中查找相应的id。我现在要做的是更新那些当前未设置/为空的属性。例如,如果新数据具有以下属性:

is_alive = True
bought = '1965-03-14'
color = None
name = 'norwegian'
id = 17
数据库中的数据有:

is_alive = False
bought = None
color = 'blue'
name = ''
id = 17

我想更新购买日期和名称(未设置或为空),但不更改is_alive状态。在这种情况下,我可以在单独的类实例中获取新的和旧的数据,手动创建属性列表并逐个比较,必要时进行更新,最后将结果保存到数据库中。然而,我觉得可能有更好的方法来处理这个问题,它也可以用于任何具有任何属性的类。有吗?

MySQL解决方案:

UPDATE my_table SET  
    bought = ( case when bought is NULL OR bought = '' ) then ? end )
  , name   = ( case when name   is NULL OR name   = '' ) then ? end )
  -- include other field values if any, here
WHERE
  id = ?
使用脚本语言设置参数值。

如果参数与旧值匹配,则默认情况下不会执行更新。

谢谢。但是,在这种情况下,我的示例中的is_alive参数不会被替换为新参数吗?除非您为更新设置特定字段,否则它不会在表中更改。因此,我仍然需要首先获取DB条目,以确定是否应该更新is_alive?然后,我可以像问题末尾提到的那样进行常规更新,并且不需要选择MySQL级别的任何字段……因为您手中已经有旧的和实例的数据,您可以检查
是否处于活动状态
是否需要任何更新。如果是,请按照我在回答中的建议,在
update
语句中设置相同的值。