Search code examples
pythondjangostringformsmodels

Increase model integer field according to repetition of words


Let's say I have two models, a Box model and a Thing model. The last one has Box as a Foreign Key. Each Box works as a container of string objects the user can add using a ModelForm. The models.py should be something like this:

models.py

class Box(models.Model):
name = models.CharField(max_length=120, unique=True)

def __str__(self):
    return self.name

class Things(models.Model):
    box = models.ForeignKey(Box)
    name = models.CharField(max_length=120)
    thing_number = models.PositiveIntegerField(default=1)

    def __str__(self):
        return self.name

Now, for each time a user insert the same string into the Form, I'd like to increase the "thing_number" Integer field by 1. Is there an easy way to do so?


Solution

  • I think you should make the field thing_number of Thing default to zero. If you do this, then you can increase the Thing number by

    thing, created = Things.objects.get_or_create(box=your_box, name=thing_name)
    thing.things_number += 1
    thing.save()
    

    other wise:

    thing, created = Things.objects.get_or_create(box=your_box, name=thing_name,
                                                  default={'thing_number':0})
    thing.things_number += 1
    thing.save()
    

    ---- extra

    As @e4c5 said the code above may cause race condition, then the code can be change like this:

    Things.objects.get_or_create(box=your_box, name=thing_name, default={'thing_number':0})
    Things.objects.filter(box=your_box, name=thing_name).update(thing_number=F('thing_number') + 1)