Django: check whether an object already exists before adding


Question

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

Thanks!

1
26
11/30/2009 5:29:05 PM

Accepted Answer

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.

38
11/30/2009 5:39:15 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon