Django: check whether an object already exists before adding

后端 未结 5 767
半阙折子戏
半阙折子戏 2021-01-31 17:19

This is a pretty simple Django question, but I can\'t find the answer in the Django docs, despite lots of hunting!

How do I check whether an object already exists, and o

5条回答
  •  时光说笑
    2021-01-31 17:52

    You can use get(), but you'll have to wrap it with try-except like this:

    try:
        obj = UserToUserRole.objects.get(from_user=current_user, to_user=user, role='follow')
    except UserToUserRole.DoesNotExist:
        # here write a code to create a new object
    

提交回复
热议问题