[Django] update_or_create usage scene

update_or_create

Role is to prevent repetition. When you add data to go to the query, if not creating, if there is updated.

update_or_create instance storage usage and password

create method

If id is None will be created successfully

General distal band id - create
without id - update

You can create and update to merge it?

Traditional create and update

  • Normal scene
    the front post to data, no id is created, there id is updated.
    Presumably also lacks the problem.

  • diy scene

obj, created = Person.objects.update_or_create(
    first_name='John', last_name='Lennon',
    defaults={'first_name': 'Bob'},
)

这就要求model, unique_together ('last_name', 'first_name')
  • update_or_create
这个规则是: 

update_or_create(defaults=None, **kwargs)

执行规则: filter kwargs,create/update defaults
返回值为元组: (object, created),object为新建或者更新的对象,created为一个布尔值,表示是新建还是更新,True为新建

Example of use: password example


Of course, such, it can create and update routine to operate alone. Because whether with id.

Reference:
Django view of the implementation of sql statement

Guess you like

Origin www.cnblogs.com/iiiiiher/p/11646309.html