I would like to set a default value for a model field that depends on the result of a database query. To achieve this, I tried the following:
def get_default_value():
try:
return SomeOtherModel.objects.all().aggregate(Max('somevalue'))['somevalue__max'] + 1
except:
return 0
class FixedTargetSerializer(serializers.ModelSerializer):
position = PointField(default=None)
dependent_value = serializers.IntegerField(default=get_default_value())
class Meta:
model = FixedTarget
fields = '__all__'
However, the function call is only evaluated once and, independent of changes taking place in the database, always the same value (that was the correct one on the first call) is used as default. Only after restarting the (development) server, the new correct value from the database is used in subsequent api calls. Documentation at http://www.django-rest-framework.org/api-guide/fields/#default however mentions the following:
May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments.
So where is my mistake? What is the appropriate way to set a default value to a field that is not set in a post request and depends on a database query?
The problem is in your model definition. You mentioned the default
value as a function
, which return a value, and while the migration, DB considered it as a Hard-coded default value instead of dynamic default value.
So change your default value to
default=get_default_value
from
default=get_default_value()
Full model definition
class FixedTargetSerializer(serializers.ModelSerializer):
position = PointField(default=None)
dependent_value = serializers.IntegerField(default=get_default_value) # don't put paranthesis [ie, "()"] for the function
class Meta:
model = FixedTarget
fields = '__all__'
Image reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With