Reputation: 2738
I have next model:
class People(models.Model):
name = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
In views.py
-When I try this one:
if People.objects.get(id=my_id):
o=People.objects.get(id=my_id)
oh=o.name
else:
send_notification_to_add_that_id(my_id)
I get this:
People query matching does not exist.
What I want is that Query the my_id
in my People
table, if there is a match with that record get the id
, else trigger the send_notification_to_add_that_id
method.
When first "if conditions" does not have such a record, i am getting above error. How to by pass this issue? What is the good approach to know existence of a record in a table ?
Upvotes: 0
Views: 57
Reputation: 53998
It's throwing an exception:
If there are no results that match the query, get() will raise a DoesNotExist exception.
so you need to handle it:
try:
People.objects.get(id=my_id)
except People.DoesNotExist:
send_notification_to_add_that_id(my_id)
alternativly you could do
people = People.objects.filter(id=my_id)
if people.exists():
person = people[0]
as filter
doesn't raise an exception if there are no results - it simply returns an empty QuerySet
but this runs the risk of returning more then one object, so it doesn't make as much sense as the first example.
As an aside, it makes more sense to call your model Person
instead of People
as that is what is being represented by your model or in the case of the DB, each row in your table.
Upvotes: 4