UpdateView that creates or increments existing instance

Viewed 40

I have a model that keeps track how much items have been "bought" at a certain value. For example, one could think of items as stocks, value as the price they have been bought at.

class Inventory(models.Model):
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField()
    value = models.PositiveIntegerField()

    class Meta:
        db_table = 'app_version'
        constraints = [
            models.UniqueConstraint(fields=['item', 'value'], name='unique valued items')
        ]

Now, I'm trying to write a class-based Create/UpdateView in which one simply declares which item has been bought at what price. Then, the view should either create a new instance or increment an existing instance's quantity.

I already figured out that an UpdateView might be the best start as I can overwrite the get_object method to have this "create or update" behaviour. However, I'm not sure how to do the incrementing.

Perhaps I'm also completely on the wrong track and there is a much simpler solution I am missing here. It would be great to get some ideas and input on how to approach this problem.

Thank you so much!

1 Answers

Just use get_or_update method. It allows you to know it's new instance or from db. But if you want to create an api, it's the better way to use django rest framework. It ships with a lot of build-in tools for quick api creation.

Related