djangobusiness-rules

django: ManyToMany: Updating and Insert Business rules


Note: New to django. Doing my with project with it. So I certainly lack many understand and the answer could be trivial.

I have a ManyToMany relationship. I have trouble coming up with an analogy but on the "main" side we have a container which contains one or more items. In my case the items aren't "real" things but more like a "template" and templates are unique. This is the background.

The business rules are that changes only happen and are initiated on the container side. So the form shows a container an it's items. A user can change one of the items. If an item in a container changes, the item instance (row in database) must not change, as said, it's a template used in many other containers. So the logic must be that if a user changes an item, a lookup is done if it already exists and if yes, instead of updating the current item, reuse the existing one. If it doesn't exist, create a new one and use that. But under no circumstance should the existing one be changed.

How and where (at which level) can I achieve this? I would really like to keep this out of the model itself (and hence not override the models save method) but do it in some type of service class.


Solution

  • Not really an answer but it seems with how django works doing this in the models save() method is the correct way to go.