Django: check whether an object already exists before adding
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.
Django - Checking if objects exists and raising error if it does
The problem is get
returns an object, but exists
only works with querysets. A Model.DoesNotExist
error will be raised when you use get
and the object does not exist.
You should use filter
instead of get
:
qs = SomeModel.objects.filter(quote_number = quote)
if qs.exists():
...
else:
...
Checking for object if it already exists in manytomany field
you are comparing User
object to User
's name (string).
value == User.objects.get(pk=user_id).name
which will fail always.Try this:
value.name == User.objects.get(pk=user_id).name
Check if an object exists
Since filter
returns a QuerySet
, you can use count to check how many results were returned. This is assuming you don't actually need the results.
num_results = User.objects.filter(email = cleaned_info['username']).count()
After looking at the documentation though, it's better to just call len on your filter if you are planning on using the results later, as you'll only be making one sql query:
A count() call performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result (unless you need to load the objects into memory anyway, in which case len() will be faster).
num_results = len(user_object)
Check if Many to Many exists in django?
We can prevent fetching the related student of the user in case we want to remove the university from the wishlist. This is usually more safer since a User
that has no related student will then not raise an error:
university = University.objects.get(id=pk)
if university.student_set.filter(user=request.user).exists():
Student.wishlist.through.objects.filter(
university=university,
student__user=request.user
).delete()
else:
request.user.student.wishlist.add(university)
We can slightly boost efficiency in the .remove(...)
path by not fetching the .student
of the user, and thus implement this as:
Identifying if object already exists in CreateView
So, the solution I implemented had to go to the ModelForm
:
class LabelForm(forms.ModelForm):
class Meta:
model = Label
fields = ('name',)
def clean(self):
if Label.objects.filter(name=self.cleaned_data['name'].lower()).exists()
raise forms.ValidationError('Label exists!')
return self.cleaned_data
Related Topics
Python Format Size Application (Converting B to Kb, Mb, Gb, Tb)
Saving the Output of a Python Program
How to Convert Datetime by Removing Nanoseconds
Easiest Way to Ignore Blank Lines When Reading a File in Python
Can Anyone Explain Me What This Python 3 Command Do
How to Install a Module for All Users With Pip on Linux
Decode Utf-8 Encoding in Json String
How to Delete All Columns in Dataframe Except Certain Ones
Efficient Way to Unnest (Explode) Multiple List Columns in a Pandas Dataframe
Pytest Cannot Import Module While Python Can
Python: [Errno 10054] an Existing Connection Was Forcibly Closed by the Remote Host
How to Read Numbers from File in Python
How to Install Python Packages from the Tar.Gz File Without Using Pip Install
How to Use Chrome Webdriver in Selenium to Download Files in Python
How to Suppress Scientific Notation When Printing Float Values