V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
magine
V2EX  ›  Django

django 有没有内置用字典更新模型的方法

  •  
  •   magine ·
    Ma233 · 2014-04-25 16:46:11 +08:00 · 4205 次点击
    这是一个创建于 3646 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如 字典A 存有要更新的键值对,然后:

    Model_foo.objects.get(pk=some_pk).update_by_dict(dict_A)
    8 条回复    2018-07-11 09:02:34 +08:00
    yueyoum
        1
    yueyoum  
       2014-04-25 16:54:28 +08:00   ❤️ 1
    Model_foo.objects.filter(pk=some_pk).update(**dict_A)
    yueyoum
        2
    yueyoum  
       2014-04-25 16:55:09 +08:00   ❤️ 1
    当然,A 的key 只能是 Model_foo的 fields, 如果有key不是,自己去除
    magine
        3
    magine  
    OP
       2014-04-25 18:21:56 +08:00
    @yueyoum get()获取的单个对象也能用吗?
    allenling
        4
    allenling  
       2014-04-26 00:28:24 +08:00   ❤️ 1
    不是有个save(update_fields=[some_fields])吗?
    yueyoum
        5
    yueyoum  
       2014-04-26 14:33:35 +08:00   ❤️ 1
    @magine

    没记错的话, update 只能用在 queryset 上, get 获取的是单个对象 不是 queryset ,所以不能用。

    filter().update() 就行, 翻译成 SQL就是

    update TABLE set A=1, B=2 where id = ...
    magine
        6
    magine  
    OP
       2014-05-03 08:55:48 +08:00
    @yueyoum

    theType, created = Type.objects.get_or_create(
    num=new_type_dic['num'],
    defaults=dict(
    name=new_type_dic['name'],
    manufacturer=new_type_dic['manufacturer'],
    pattern=new_type_dic['pattern'],
    standard=new_type_dic['standard'],
    ))

    if created==True:
    info['new_type_num'] = theType.num
    else:
    Type.objects.filter(num=theType.num).update(new_type_dic)

    先检查是否已有设备类型(Type),如果没有就新建,并在info中留下记录,否则就用字典数据更新。
    这样写有没有冗余?或者说不合理?
    magine
        7
    magine  
    OP
       2014-05-03 09:11:56 +08:00
    https://gist.github.com/Ma233/f9a763e5199109503174

    贴一份容易看的代码出来……
    37Y37
        8
    37Y37  
       2018-07-11 09:02:34 +08:00
    __dict__.update 了解一下
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3380 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 11:41 · PVG 19:41 · LAX 04:41 · JFK 07:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.