4👍
✅
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(....)
- [Django]-Overriding the save() method of a model that uses django-mptt
- [Django]-Removing from a Haystack/Xapian Index with update_index –remove
- [Django]-Haystack / Whoosh Index Generation Error
- [Django]-Problem trying to achieve a join using the `comments` contrib in Django
- [Django]-Django Apache wsgi changes python version
1👍
The problem with your code is that the MyModel.objects.get
will raise DoesNotExist
, try using exists
instead:
if not MyModel.objects.filter(surname='foo').exists():
management.call_command('loaddata', 'Bootstrap_data', verbosity=0)
- [Django]-Try/except database query in django
- [Django]-Django – Can a POST and GET request be returned in one HttpRequest?
- [Django]-Search multiple fields of django model without 3rd party app
- [Django]-Django user profile database problem
- [Django]-Django set multiply function for single url
Source:stackexchange.com