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.
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(....)
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