django update_or_create gets “duplicate key value violates unique constraint ”

前端 未结 3 2155
天涯浪人
天涯浪人 2021-02-19 21:03

Maybe I misunderstand the purpose of Django\'s update_or_create Model method.

Here is my Model:

from django.db import models
import datetime
from vc.mode         


        
3条回答
  •  北荒
    北荒 (楼主)
    2021-02-19 21:28

    This is already answered well in the above.

    To be more clear the update_or_create() method should have **kwargs as those parameters on which you want to check if that data already exists in DB by filtering.

    select some_column from table_name where column1='' and column2='';

    Filtering by **kwargs will give you objects. Now if you wish to update any data/column of those filtered objects, you should pass them in defaults param in update_or_create() method.

    so lets say you found an object based on a filter now the default param values are expected to be picked and updated.

    and if there's no matching object found based on the filter then it goes ahead and creates an entry with filters and the default param passed.

提交回复
热议问题