In my app, when users enter an item they may choose one or more categories
for the item by checking one or more checkboxes. When the form processes I
cycle through the value of the checkboxes. If none have been checked, I
want to put a default category for the item in the database named "not
sure". A hack for this, which I started with during development, was to
enter a record in the category table for "not sure", note the id, and hard
code the id. Clearly that was bad...
So, in the db.py model I have done this instead:
no_category = jodb.category(name = "not sure")
if no_category:
no_category_id = no_category.id # use no_category_id to force "not
sure" as category when needed
else:
no_category_id = jodb.category.insert(name = "not sure")
This makes the variable no_category_id available in any controller. It
ensures that "not sure" is always a valid category. Assuming the database
and table persist, then the id for "not sure" will remain the same. If I
(or a helper) inadvertently deletes the "not sure" category, then the next
time through the "not sure" category id will have a different id and some
items might reference a non-existent category (which is ok with an outer
join, but will look odd). I suppose I better put in a check so that
no_category_id is never deleted.
Does this appear to be a reasonable way to accomplish this? The cost is
doing a query every time the site is reached, but then lots more queries
are done to generate the pages users actually see.
Thanks for any suggestions.
--