Django: check whether an object already exists before adding

后端 未结 5 769
半阙折子戏
半阙折子戏 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 18:09

    There's a helper function for this idiom called 'get_or_create' on your model manager:

    role, created = UserToUserRole.objects.get_or_create(
        from_user=current_user, to_user=user, role='follow')
    

    It returns a tuple of (model, bool) where 'model' is the object you're interested in and 'bool' tells you whether it had to be created or not.

提交回复
热议问题