-1

I have the following code:

from django_app.models import Model
def func_name():
    name = "name"
    if Model.objects.filter(name=name).count() > 1:
        raise ValidationError("This name already exists.")
    else:
        return name

Now I want to turn it into a one-liner. This is what I did:

from django_app.models import Model
def func_name():
    name = "name"
    raise ValidationError("This name already exists") if Model.objects.filter(name=name).count() > 1 else return name

But this gives me a syntax error.
Is such an implementation possible in Python?

Saman
  • 29
  • 1
  • 8

1 Answers1

1

Because it is impossible. This is the philosophy of Python: readable code. Your code

raise ValidationError("This name already exists") if Model.objects.filter(name=name).count() > 1 else return name

will be executed as

if Model.objects.filter(name=name).count() > 1:
    raise ValidationError("This name already exists")
else:
    raise (return name)

which is not valid

Also you can't avoid this because raise doesn't return any data.

11_22_33
  • 116
  • 1
  • 15