简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM