Karl
Karl

Reputation: 743

Updating foreign key field in Django

I have a form that displays a drop down for a foreignkey field. The form saves the users selection, however I want the view to update the database entry rather than inserting a new one. Whats the best way to go about this?

Current function:

def formset_valid(self, formset):
    self.object = formset.save()
    self.object.save()
    return HttpResponseRedirect(self.get_success_url())

I have tried something like this:

d = RevisionDefaultType.objects.get(id=1)
n = RevisionSettings.objects.get(self.object)
d.defaultrevisiontype = n
d.save()

But it throws an error that the data being updated is not an instance.

Upvotes: 3

Views: 9077

Answers (2)

Kasravnd
Kasravnd

Reputation: 107347

You must add force_update=True to your save() function.

For more info about How Django knows to UPDATE vs. INSERT see this link in django's documentation.

Upvotes: 2

Karl
Karl

Reputation: 743

I managed to tweak the update example from https://docs.djangoproject.com/en/dev/topics/db/queries/#saving-foreignkey-and-manytomanyfield-fields. This seems to be working as desired.

    def formset_valid(self, formset):

        self.object = formset.save(commit=False)
        revdefault = RevisionDefaultType.objects.get(pk=1)
        revget = RevisionSettings.objects.get(global_revision_type=self.object)
        revdefault.defaultrevisiontype = revget
        revdefault.save()

        return HttpResponseRedirect(self.get_success_url())

Thanks again for the help.

Upvotes: 2

Related Questions