G
G
grecha102020-11-17 13:00:49
Django
grecha10, 2020-11-17 13:00:49

How to update a unique field in ModelAdmin with a non-unique value on bulk data update?

There is a model with a unique field filled with unique values.

class MyModel(models.Model):
    uniqfield = models.IntegerField('Уникальное поле', unique=True)


The admin panel has a class inherited from ModelAdmin for editing this model.
@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    list_display = ('uniqfield',)
    
    def save_model(self, request, obj, form, change):
        try:
            obj.save()
        except
            # соообщение об не уникальности вставляемых значений


I want to simultaneously change, for example, two values ​​in this field to each other. For example:
pk=1, uniqfield=1
pk=2, uniqfield=2

я в форме редактирования на странице меняю их местами и хочу получить:
pk=1, uniqfield=2
pk=2, uniqfield=1


obj.save() throws a predictable exception due to non-unique values, i.e. when you update the first value in the table, it is still present.

How to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-11-17
@bacon

1. hands pk=1 to assign 3, pk=2 to assign 1, pk=1 to assign 2
2. write admin action not to do it manually
PS exclude null from uniqueness and then it can be used instead of 3.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question