nassim
nassim

Reputation: 1555

Django Add default value to model field having the value of another field

I want to add a field to my django model and I want its default value to be equal to the primarykey value (id), but I want it to apply to all already existing records in my database.

class ModelB(models.Model):
  id= models.IntegerField()
  index = models.IntegerField(default=" i want something here to get id value")

I found previous questions covering this but the answers only give a solution where you have to add a method that adds the value on save. In my case I want this value to be applied to previously saved records also.

Please if you have an idea I'd appreciate your help, thanks.

Upvotes: 0

Views: 280

Answers (1)

EE2021
EE2021

Reputation: 133

You should preform this step by overriding the save method. You can also create a function that updates all the past models.

models.py

class ModelB(models.Model):
  id = models.IntegerField()
  index = models.IntegerField(null=True)
  def save(self, *args, **kwargs):
    if not self.index:
      self.index = self.id
    super().save(*args, **kwargs)

To create a 'refresh' function, try this:

admin.py

...
from .models import ModelB

def refresh_objects(modeladmin, request, queryset):
    for object in queryset:
        object.save()

refresh_objects.short_description = "Update selected objects."

class ModelBAdmin(admin.ModelAdmin):
    actions = [refresh_objects]

admin.site.register(ModelB, ModelBAdmin)

Now, simply head to the admin site, select all the models to refresh, and run this action. (It can be found in the dropdown)

Upvotes: 1

Related Questions