Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django object existence

I wanted to check that object exists in the db, and if it does not exist, to add it to the database. I tried:

if not MyModel.objects().get(surname='foo'): 
     management.call_command('loaddata', 'Bootstrap_data', verbosity=0)#adds this object from fixtures

But I get a query error from db(sqlite3). How can this way of object validation be resolved?

The error is:

DoesNotExist at /
MyModel matching query does not exist.

It is because there is no object with this surname in the db.

like image 655
Feanor Avatar asked May 18 '26 15:05

Feanor


1 Answers

Typically you'd use get_or_create.

model_instance = MyModel.objects.get_or_create(surname='foo')

You shouldn't really be using management.call_command for something like this.

That said, if I've misunderstood and you have a good reason, try this:

try:
    MyModel.objects.get(surname='foo')
except MyModel.DoesNotExist:
      management.call_command(....)

OR

if not MyModel.objects.filter(surname='foo').exists():
      management.call_command(....)
like image 81
Matt Luongo Avatar answered May 20 '26 03:05

Matt Luongo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!