Home > Software design >  Django: Changing of value of particular fields in previous instances of model if particular instance
Django: Changing of value of particular fields in previous instances of model if particular instance

Time:12-09

I' m creating small django project. Is any way to change value of particular fields in previous instances of particular model?

class Fruit (models.Model):
    name=models.CharField(max_length=40)
        amount=models.IntegerField()

So far for example i have three instances of my model.

[0 Object{ "model": "Fruit","pk": 1,"fields": {"name": "Banana", "amount": "2"}},
1 Object{ "model": "Fruit","pk": 2,"fields": {"name": "Apple", "amount": "2"}},
2 Object{ "model": "Fruit","pk": 3,"fields": {"name": "Mango", "amount": "1"}}]

And i decided that fourth instance will be Orange in amount 3.

[0 Object{ "model": "Fruit","pk": 1,"fields": {"name": "Banana", "amount": "2"}},
1 Object{ "model": "Fruit","pk": 2,"fields": {"name": "Orange", "amount": "2"}},
2 Object{ "model": "Fruit","pk": 3,"fields": {"name": "Orange", "amount": "1"}}
3 Object{ "model": "Fruit","pk": 4,"fields": {"name": "Orange", "amount": "3"}}]

As you see my goal is to change all previous names of fruits to Orange in case of creating of instance with Orange as name until Banana occurs so banana remains unchanged.

Is there any way to do something like that?

CodePudding user response:

you can loop over your Fruit object and change all names based on condition

for item in Fruit.objects.all():
   if item.name == "Banana":
      pass
   else:
      Fruit.objects.update(..update values)

CodePudding user response:

After the new instance is created, you can loop through all instances in reverse order until the keyword (e.g. "Banana") is found. See documentation for reverse method. Break the loop if the keyword is found, else change the fruit name (e.g. to "Orange").

for fruit in Fruit.objects.all().reverse():
    if fruit.name == "Banana":
        break
    else:
        fruit.name = "Orange"
        fruit.save()

This solution assumes you want to do the changes immediately after an instance is created (so in your example the fourth instances would be the last instance).

  • Related