[Django]-Django object existence

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

1👍

if not MyModel.objects.filter(surname='foo').exists()

RTFriendlyM

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)
👤César

Leave a comment