Alex Rivera | Logout

Django: check whether an object already exists before adding

Asked 2009-11-30T17:26:39.947
31

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()
Edit
Report

1 Answer

3

If you're using a recent version of Django, you can use the unique_together option to the UserToUserRole model, and then use the get_or_create() method Joe Holloway showed. This will guarantee that you can't get a duplicate.

answered 2009-11-30T17:42:02.830

Your Answer