Save multiple objects with a unique attribute using Django formset

荒凉一梦 提交于 2019-12-06 03:25:55

It seems not possible to constraint the order on the database level. I'm not saying it's not possible, but I don't know how.

For now, I added a check in my formset. I'll leave it here in case someone has a similar problem.

class BaseSettingFormSet(BaseInlineFormSet):
    '''FormSet to update the order of Settings in a Machine'''

    def clean(self):
        '''Checks if there are no two Settings with the same order.'''
        if any(self.errors):
            return
        orders = []
        for form in self.forms:
            if form.cleaned_data:
                order = form.cleaned_data['order']
                if order in orders:
                    form.add_error('order', _('The order of each setting must be unique'))
                else:
                    orders.append(order)

I was able to achieve it using deferred constraint (works for Postgres DB only)

Check this answer on how to set it up: https://stackoverflow.com/a/56644496

And afterwards you want to:

  1. set self._validate_unique = False in the ModelForm (it's set to True during clean() method)
  2. Wrap saving of the formset in transaction.atomic() block (this will trigger the deferred constraint)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!