I have a Django model called StaffSettings which contains various configuration options for users in my Django app. Each User has at most one entry in the StaffSettings table.
Assume that one setting is default_year_level, and I have code for my user objects like:
def set_default_year_level(u, year_level):
obj, _created = StaffSettings.objects.get_or_create(user=u)
obj.default_year_level = year_level
obj.save()
I would prefer the body of the function to fit onto one line because it seems like a common use case, but if I defined it as
def set_default_year_level(u, year_level):
StaffSettings.objects.filter(user=u).update(default_year_level=year_level)
which works fine if the user in question already has a row in the StaffSettings table, but it won't create the relevant row if it doesn't exist.
What is the idiomatic/best way to code this? (e.g. Is there some sort of filter_or_create
function? Or do other people write decorators/helper functions to handle this idiom?)