title: Django Rest Framework Serializer how to set a default value depending on a database query
body: <p>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:</p>
  
  <pre><code>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__'
  </code></pre>
  
  <p>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 <a href="http://www.django-rest-framework.org/api-guide/fields/#default" rel="nofollow noreferrer">http://www.django-rest-framework.org/api-guide/fields/#default</a> however mentions the following: </p>
  
  <blockquote>
    <p>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. </p>
  </blockquote>
  
  <p>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?</p>