Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: check whether an object already exists before adding

Tags:

python

django

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() 
like image 430
AP257 Avatar asked Nov 30 '09 17:11

AP257


People also ask

How to check if model exists Django?

Use the exists() Method to Check if an Object Exists in the Model in Django.

How do I check if a class object exists?

Using isinstance() function, we can test whether an object/variable is an instance of the specified type or class such as int or list. In the case of inheritance, we can checks if the specified class is the parent class of an object.

Does exist in Django?

exists() is useful for searches relating to both object membership in a QuerySet and to the existence of any objects in a QuerySet, particularly in the context of a large QuerySet.


1 Answers

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.

like image 151
Joe Holloway Avatar answered Oct 02 '22 16:10

Joe Holloway