In django, I'm trying to do something like this:
# if form is valid ...
article = form.save(commit=False)
article.author = req.user
product_name = form.cleaned_data['product_name']
try:
article.product = Component.objects.get(name=product_name)
except:
article.product = Component(name=product_name)
article.save()
# do some more form processing ...
But then it tells me:
null value in column "product_id" violates not-null constraint
But I don't understand why this is a problem. When article.save()
is called, it should be able the create the product then (and generate an id).
I can get around this problem by using this code in the except
block:
product = Component(name=product_name)
product.save()
article.product = product
But the reason this concerns me is because if article.save()
fails, it will already have created a new component/product. I want them to succeed or fail together.
Is there a nice way to get around this?