Alex Lord Mordor
Alex Lord Mordor

Reputation: 3050

Django - Save model inside transaction with unsaved foreignkey

I have two Models, one of them has a ForeignKey to the other, the idea is to save them inside a transaction but it gives me an error.

These are my models:

class Parent(models.Model):
    name = models.CharField(...)
    ...

class Child(models.Model):
    parent = models.ForeignKey(Parent)
    ...

this is my view

@transaction.atomic()
def save_parent(request):
    try:
        parent = Parent(name=request.POST.get('name'),other_fields).save()
        child = Child(parent=parent,other_fields).save()
        ...
    except:
        pass

I have looked for transaction savepoints but I dont understand them. My main goal is to save both or don't save anything

Any Ideas?

Upvotes: 0

Views: 1976

Answers (1)

Othman
Othman

Reputation: 3018

You are not saving the objects correctly. Try this

parent = Parent(name=request.POST.get('name'),other_fields)
parent.save()
child = Child(parent=parent,other_fields)
child.save()

Or use the create method inside the manager.

parent = Parent.objects.create(name=request.POST.get('name'),other_fields)
child = Child.objects.create(parent=parent,other_fields)

Upvotes: 2

Related Questions