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()
Use the exists() Method to Check if an Object Exists in the Model in Django.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With