I have a Django model called StaffSettings that contains various configuration options for users in my Django application. Each user has no more than one entry in the StaffSettings table.
Suppose one parameter has a default value of year_level, and I have code for my custom objects, for example:
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 function body to be placed on one line, because this seems like a normal 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 who has the question has a row in the StaffSettings table, but it will not create the corresponding row if it does not exist.
What is the idiomatic / best way to code this? (for example, is there any filter_or_create function? Or do other people write decorators / helper functions to handle this idiom?)
bryn
source share