nodes: 0, module; 1, function_definition; 2, function_name:_sort_by_unique_fields; 3, parameters; 4, block; 5, identifier:model; 6, identifier:model_objs; 7, identifier:unique_fields; 8, expression_statement; 9, expression_statement; 10, function_definition; 11, return_statement; 12, comment:"""
      Sort a list of models by their unique fields.
  
      Sorting models in an upsert greatly reduces the chances of deadlock
      when doing concurrent upserts
      """; 13, assignment; 14, function_name:sort_key; 15, parameters; 16, block; 17, call; 18, identifier:unique_fields; 19, list_comprehension; 20, identifier:model_obj; 21, return_statement; 22, identifier:sorted; 23, argument_list; 24, identifier:field; 25, for_in_clause; 26, if_clause; 27, call; 28, identifier:model_objs; 29, keyword_argument; 30, identifier:field; 31, attribute; 32, comparison_operator:field.attname in unique_fields; 33, identifier:tuple; 34, generator_expression; 35, identifier:key; 36, identifier:sort_key; 37, attribute; 38, identifier:fields; 39, attribute; 40, identifier:unique_fields; 41, call; 42, for_in_clause; 43, identifier:model; 44, identifier:_meta; 45, identifier:field; 46, identifier:attname; 47, attribute; 48, argument_list; 49, identifier:field; 50, identifier:unique_fields; 51, identifier:field; 52, identifier:get_db_prep_save; 53, call; 54, identifier:connection; 55, identifier:getattr; 56, argument_list; 57, identifier:model_obj; 58, attribute; 59, identifier:field; 60, identifier:attname
code: def _sort_by_unique_fields(model, model_objs, unique_fields):
      """
      Sort a list of models by their unique fields.
  
      Sorting models in an upsert greatly reduces the chances of deadlock
      when doing concurrent upserts
      """
      unique_fields = [
          field for field in model._meta.fields
          if field.attname in unique_fields
      ]
  
      def sort_key(model_obj):
          return tuple(
              field.get_db_prep_save(getattr(model_obj, field.attname),
                                     connection)
              for field in unique_fields
          )
      return sorted(model_objs, key=sort_key)