Django: check whether an object already exists before adding

django, python

Solution

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.

Problem

How do I check whether an object already exists, and only add it if it does not already exist? Here's the code - I don't want to add the follow_role twice in the database if it already exists. How do I check first? Use get() maybe - but then will Django complain if get() doesn't return anything? ``` current_user = request.user follow_role = UserToUserRole(from_user=current_user, to_user=user, role='follow') follow_role.save() ```

Original source