django update_or_create gets “duplicate key value violates unique constraint ”

前端 未结 3 2168
天涯浪人
天涯浪人 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:37

    You should separete your field:

    1. Fields that should be searching for
    2. Fields that should be updated

    for example: If I have the model:

    class User(models.Model):
        username = models.CharField(max_lenght=200)
        nickname = models.CharField(max_lenght=200)
    

    And I want to search for username = 'Nikolas' and update this instance nickname to 'Nik'(if no User with username 'Nikolas' I need to create it) I should write this code:

    User.objects.update_or_create(
        username='Nik', 
        defaults={'nickname': 'Nikolas'},
    )
    

    see in https://docs.djangoproject.com/en/2.0/ref/models/querysets/

提交回复
热议问题