IntegrityError: distinguish between unique constraint and not null violations

前端 未结 3 1793
误落风尘
误落风尘 2020-12-06 10:19

I have this code:

try:
    principal = cls.objects.create(
        user_id=user.id,
        email=user.email,
        path=\'something\'
    )
except Integri         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-06 11:12

    It could be better to use:

    try:
        obj, created = cls.objects.get_or_create(user_id=user.id, email=user.email)
    except IntegrityError:
        ....
    

    as in https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create

    The IntegrityError should be raised only in the case there's a NOT NULL constraint violation. Furthermore you can use created flag to know if the object already existed.

提交回复
热议问题