The system I’m building has smart groups. By smart groups, I mean groups that update automatically based on these rules:
- Include all people that are associated with a given client.
- Include all people that are associated with a given client and have these occupations.
- Include a specific person (i.e., by ID)
Each smart groups can combine any number of these rules. So, for example, a specific smart list might have these specific rules:
- Include all people that are associated with client 1
- Include all people that are associated with client 5
- Include person 6
- Include all people associated with client 10, and who have occupations 2, 6, and 9
These rules are OR’ed together to form the group. I’m trying to think about how to best store this in the database given that, in addition to supporting these rules, I’d like to be able to add other rules in the future without too much pain.
The solution I have in mind is to have a separate model for each rule type. The model would have a method on it that returns a queryset that can be combined with other rules’ querysets to, ultimately, come up with a list of people. The one downside of this that I can see is that each rule would have its own database table. Should I be concerned about this? Is there, perhaps, a better way to store this information?
Here are the models we implemented to deal with this scenario.
At first I was resistant to this solution as I didn’t like the idea of storing references to other objects in a CharField (CharField was selected, because it is the most versatile. Later on, we might have a rule that matches any person whose first name starts with ‘Jo’). However, I think this is the best solution for storing this kind of mapping in a relational database. One reason this is a good approach is that it’s relatively easy to clean hanging references. For example, if a company is deleted, we only have to do:
If the parameters were stored as serialized objects (e.g., Q objects as suggested in a comment), this would be a lot more difficult and time consuming.