简体   繁体   English

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

[英]Updating dynamically determined fields with peewee

I have a peewee model like the following: 我有一个类似下面的peewee模型:

class Parrot(Model):
    is_alive = BooleanField()
    bought = DateField()
    color = CharField()
    name = CharField()
    id = IntegerField()

I get this data from the user and look for the corresponding id in the (MySQL) database. 我从用户那里获得了这些数据,并在(MySQL)数据库中查找了相应的ID。 What I want to do now is to update those attributes which are not set/empty at the moment. 我现在想做的就是更新那些当前未设置/为空的属性。 For example, if the new data has the following attributes: 例如,如果新数据具有以下属性:

is_alive = True
bought = '1965-03-14'
color = None
name = 'norwegian'
id = 17

and the data from the database has: 并且数据库中的数据具有:

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

I would like to update the bought date and the name (which are not set or empty), but without changing the is_alive status. 我想更新购买日期和名称(未设置或为空),但不更改is_alive状态。 In this case, I could get the new and old data in separate class instances, manually create a list of attributes and compare them one for one, updating where necessary, and finally saving the result to the database. 在这种情况下,我可以在单独的类实例中获取新数据和旧数据,手动创建属性列表,并将其一一进行比较,在必要时进行更新,最后将结果保存到数据库中。 However, I feel there might be a better way for handling this, which could also be used for any class with any attributes. 但是,我觉得可能有更好的处理方法,它也可以用于具有任何属性的任何类。 Is there? 在那儿?

MySQL Solution: 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 = ?

Use your scripting language to set the parameter values. 使用脚本语言来设置参数值。
In case of the parameters matching the old values, then update will not be performed, by default. 如果参数与旧值匹配,则默认情况下将不执行更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM