V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
magine
V2EX  ›  Django

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

  •  
  •   magine ·
    Ma233 · Apr 25, 2014 · 4986 views
    This topic created in 4386 days ago, the information mentioned may be changed or developed.
    比如 字典A 存有要更新的键值对,然后:

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

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

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

    update TABLE set A=1, B=2 where id = ...
    magine
        6
    magine  
    OP
       May 3, 2014
    @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
       May 3, 2014
    https://gist.github.com/Ma233/f9a763e5199109503174

    贴一份容易看的代码出来……
    37Y37
        8
    37Y37  
       Jul 11, 2018
    __dict__.update 了解一下
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4851 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 09:57 · PVG 17:57 · LAX 02:57 · JFK 05:57
    ♥ Do have faith in what you're doing.